context = window
EventActions = context.EventActions

context.EventPage = React.createClass({

    mixins: [Reflux.listenTo(EventStore, "onEventsChanged")],


    once: false,

    getInitialState: function () {
        return {submitting: false, error: null, event: null}
    },

    parseSlug: function () {
        var path = window.location.pathname

        var pathPart = path.substring('/events/'.length)

        var query = pathPart.indexOf('?')
        if (query > -1) {
            var slug = pathPart.substring(0, query)
        }
        else {
            var slug = pathPart
        }
        return slug;

    },

    componentDidMount: function () {
        EventActions.single(this.parseSlug())
        //  new Plyr('#video');
    },

    componentDidUpdate: function () {
        if((this.isReady() || this.isErrored()) && !this.once) {

            if(!this.isErrored()) {
                try {

                    if (this.isWhiteLabel()) {
                        const player = new Plyr('#player', {
                            controls: ['play-large', 'play', 'progress', 'current-time', 'mute', 'volume', 'settings', 'pip', 'airplay', 'fullscreen'],
                            pip: true,
                            fullscreen: {
                                enabled: true,
                                fallback: true,
                                iosNative: false
                            }, title: this.title()
                        });
                        player.pip = true
                        player.playsinline = true
                    }
                }
                catch(e) {
                    console.log("error initializing video player", e)
                }
            }

            if(this.isAuthorized()) {
                var listing = document.getElementById("body-content")

                var chatElement = document.getElementById("rt-e617b4394e0e49e1c234c63161bb2e15")

                chatElement.style.overflow = 'visible'
                listing.appendChild(chatElement)
            }
            else {

                var chatElement = document.getElementById("rt-e617b4394e0e49e1c234c63161bb2e15")

                chatElement.parentNode.removeChild(chatElement)
            }
            this.once = true
        }
    },

    authorizeDone: function (response) {
        this.setState({submitting: false})
        EventActions.addAuthorization(response)
    },

    authorizeFailed: function (e) {
        if (e instanceof SyntaxError) {
            this.setState({error: 'Server error. Please try again or contact support@jamkazam.com.'})
        }
        else if (e instanceof Error) {
            this.setState({error: 'Please enter a valid Eventbrite Order ID'})
        }
        else {
            console.log("heheh", e)
        }
        this.setState({submitting: false})
    },

    handleSubmit: function (event) {
        var value = document.getElementById("order-input").value
        if (value) {
            context.JK.Rest2.authorizeLiveStream({order: value}).then((response) => {
                if (!response.ok) {
                    throw Error(response.statusText);
                }
                return response.json()
            }).then((response) => this.authorizeDone(response)).catch((jqXHR) => this.authorizeFailed(jqXHR))
            this.setState({submitting: true, error: null})
        }
        event.preventDefault();
    },

    isErrored() {
        return !!this.state.error
    },

    isReady() {
        return !!this.state.event
    },

    isAuthorized() {
        return this.isReady() ? (this.state.event.authorization || this.state.event.allow_in) : false
    },

    isNotAuthorized() {
        return false
    },

    videoCode() {
        return this.state.event.youtube_code
    },

    isWhiteLabel() {
        return this.state.event.white_label_player
    },

    title() {
        return this.state.event.title ? this.state.event.title : 'Unknown title'
    },

    description() {
        return this.state.event.description ? this.state.event.description : null
    },

    startsAt() {
        return this.state.event.starts_at ? "Starts at " + new Date(this.state.event.starts_at).toLocaleString() : null
    },

    header() {

        if (this.isErrored()) {
            return <div className="header">
                <div className="title">No event found.</div>
            </div>
        }
        else if (this.isReady()) {
            var title = this.title()
            var description = this.description()
            var descriptionElement = null
            if(description) {
                descriptionElement = <div className="description">{description}</div>
            }

            var startsAt = this.startsAt()
            var startsAtElement = null
            if(startsAt)
            {
                startsAtElement = <div className="starts-at">{startsAt}</div>
            }

            return <div className="header">
                <div className="title">{title}</div>
                {descriptionElement}
                {startsAtElement}
                <div id="powered-by-2">
                    <div>
                        <span>powered by </span>
                        <div className="powered-by"></div>
                    </div>
                </div>
            </div>
        }
        else {
            return <div className="header">
                <div className="title">Loading ...</div>
            </div>
        }
    },

    back: function() {
        if(this.isErrored() || (this.isReady() && !this.isAuthorized())) {
            return <a href="/events" id="back-link">All Events</a>
        }
        else {
            return null;
        }
    },

    body: function () {
        var video = null
        if (this.isErrored()) {
            video = null
        }
        else if (this.isReady()) {
            if (this.isAuthorized()) {
                var videoCode = this.videoCode()

                var src = "https://www.youtube.com/embed/" + this.videoCode() + "?modestbranding=true&autoplay=1&rel=0&playsinline=1&enablejsapi=1"

                if(videoCode) {
                    if(this.isWhiteLabel()) {
                        video = <div class="plyr__video-embed" id="player">
                            <iframe
                                src={src}
                                allowFullScreen={true}
                                allow="accelerometer; encrypted-media; gyroscope; autoplay; fullscreen"
                                ></iframe>
                        </div>
                    }
                    else {
                        video = <div id="player">
                            <iframe src={src} frameBorder="0"
                                    style={ { position:"absolute", top:0,left:0,width:"100%", height:"100%"} }
                                    allow="accelerometer; encrypted-media; gyroscope; autoplay"
                                    allowFullScreen={true}></iframe>
                        </div>
                    }
                }
                else {
                    video = <div id="no-player" className="no-code">
                        <div>No video yet</div>
                    </div>
                }
            }
            else {
                var notRegistered = <span className="no-register">You are not registered for this event!</span>
                var onceDone = <li>Enter your EventBrite order code at the <a href="https://www.jamkazam.com/events"
                                                                              target="_blank"> JamKazam Event
                    Registration</a> page when done registering.</li>

                var eventBriteUrl = this.state.event.event_brite_registration_url
                if (eventBriteUrl) {
                    var meat = <div>
                        {notRegistered}
                        <ol>
                            <li>Please register at <a target="_blank" href={eventBriteUrl}>EventBrite</a> to see this
                                video
                            </li>
                            {onceDone}
                        </ol>
                    </div>
                }
                else {
                    var meat = <div>
                        {notRegistered}
                        <ol>
                            <li>Please find your event at <a target="_blank"
                                                             href="https://www.eventbrite.com/d/online/jamkazam/">EventBrite</a>
                                and register for this event.
                            </li>
                            {onceDone}
                        </ol>
                    </div>
                }
                video = <div id="no-player" className="no-code">
                    {meat}
                </div>
            }
        }
        else {
            video = <div id="no-player"></div>
        }

        return video
    },

    render: function () {

        var header = this.header()

        var body = this.body()

        var back = this.back();

        var response = <div className="EventPage">
            <div id="header">
                <div className="logo-holder"></div>
            </div>
            <div id="body-content">
                <div id="top-container">
                    {header}
                </div>
                <div></div>
                <div></div>
                <div className="listing" id="listing">
                    <div className="listing-content">
                        {body}
                    </div>
                </div>
                <div></div>
            </div>
            {back}
        </div>
        return response
    },

    onEventsChanged: function (allEvents) {
        var event = null;
        if (allEvents && allEvents.events && allEvents.events.entries && allEvents.events.entries.length > 0) {
            event = allEvents.events.entries[0]
        }

        console.log("event change", event, allEvents)
        this.setState({event: event, error: allEvents.events_error})
    }
})