const s = io(window.socketHost)
let tmp = ""
let tmp2 = false
let backgroundImage = 1
let reloadPage = false
msv().loading.params("#dddddd", "img/loading.gif", 0.6)


const LoginView = React.createClass({
  render () {
    return (
            <div className="loginTable" id="loginTable">
                <div className="loginTableBackground" id="loginTableBackground1"></div>
                <div className="loginTableBackground" id="loginTableBackground2"></div>
                <div className="loginTableBackground" id="loginTableBackground3"></div>
                <div className="loginTableBackground" id="loginTableBackground4"></div>
                <div className="loginBlock" id="loginBlock">
                    <p>Login to your account</p>
                    <input id="login" type="text" name="login" placeholder="Login"/>
                    <input id="password" type="password" name="login" placeholder="Password"/>
                    <button onClick={this.checkLogin}>Log-in</button>
                </div>
            </div>
    )
  },
  checkLogin () {
    tmp = `${Math.floor((Math.random() * 100000000000) + 1000000000)}_tmp`
    s.emit("authorize", { l: document.getElementById("login").value, p: document.getElementById("password").value, id: tmp })
    msv().loading.params("#dddddd", "img/loading.gif", 0.6)
    msv(".loginBlock").loading.start()
  },
})
const MainView = React.createClass({
  getInitialState () {
    return {
      timer: {},
    }
  },
  render () {
    return (
            <div>
                <LeftPart/>
                <div id="rightPart0"><RightPart moduleURL={this.props.moduleURL} module={this.props.module}/></div>
                <div id="rightPartLoading">
                    <div className="loader">
                        <div className="loader-inner">
                            <div className="loader-line-wrap">
                                <div className="loader-line"></div>
                            </div>
                            <div className="loader-line-wrap">
                                <div className="loader-line"></div>
                            </div>
                            <div className="loader-line-wrap">
                                <div className="loader-line"></div>
                            </div>
                            <div className="loader-line-wrap">
                                <div className="loader-line"></div>
                            </div>
                            <div className="loader-line-wrap">
                                <div className="loader-line"></div>
                            </div>
                        </div>
                    </div>
                </div>
                <Window window={this.props.window} windowName={this.props.windowName} windowBody={this.props.windowBody}/>
                <Timer/>
            </div>
    )
  },
})


/* MAIN VIEW */
const LeftPart = React.createClass({
  getInitialState () {
    return {
      modules: [],
    }
  },
  componentDidMount () {
    const a = this
    s.emit("getModules", tmp)
    s.on("getModules", (data) => {
      bios.modules = data
      if (a.isMounted()) {
        a.setState({
          modules: data,
        })
      }
    })
  },
  render () {
    const Menu = []
    const cook = bios.cookie.get("menuID") === "false"
    const iStyle = {
      width: "50px",
      border: "solid transparent 0px",
    }
    const pStyle = { display: "none" }
    if (this.state.modules.length != 0) {
      i = 0
      do {
        const e = this.state.modules[i]
        if (cook) {
          Menu.push(<li onClick={this.module.bind(this, i)}><i className={e.icon} style={iStyle}/><p style={pStyle}>{e.name}</p></li>)
        } else {
          Menu.push(<li onClick={this.module.bind(this, i)}><i className={e.icon}/><p>{e.name}</p></li>)
        }
      } while (i++ <= this.state.modules.length - 2)
    }

    return (
            <div id="leftPart">
                <img onClick={this.reload} src="img/logo.png"/>
                <img onClick={this.reload} src="img/logo_mini.png"/>
                <ul>{Menu}</ul>
                <div>
                    <button onClick={this.menu} title="Schować menu"/>
                    <button onClick={this.settings} title="Ustawienia CRM"/>
                    <button onClick={this.exit} title="Wylogować się"/>
                </div>
            </div>
    )
  },
  menu () {
    const w = document.body.clientWidth
    const w0 = 430
    if (bios.menuID) {
      $("#leftPart").animate({ width: "50px" }, 300)

      if (w < w0) {
        $("#rightPart").animate({ width: `${w - 50}px` }, 300)
        $("#rightPart").show(0)
      } else {
        $("#rightPart").animate({ width: `${w - 50}px` }, 300)
      }

      $("#leftPart li i").css("width", "50px")
      $("#leftPart li i").css("border", "0px")
      $("#leftPart li p").hide(0)
      $("#leftPart div button:nth-child(1)").css("width", "100%")
      $("#leftPart div button:nth-child(2)").hide(0)
      $("#leftPart div button:nth-child(3)").hide(0)
      $("#leftPart img:nth-child(1)").hide(0)
      $("#leftPart img:nth-child(2)").show(0)
      $("#leftPart div").css("width", "50px")
      bios.cookie.set("menuID", false, 1)
      bios.menuID = false
    } else {
      if (w < w0) {
        $("#leftPart").animate({ width: `${w}px` }, 300, () => {
          $("#leftPart li p").show(0)
          $("#leftPart div button:nth-child(2)").show(0)
          $("#leftPart div button:nth-child(3)").show(0)
        })
        $("#rightPart").animate({ width: `${w - 220}px` }, 300)
        $("#rightPart").hide(0)
      } else {
        $("#leftPart").animate({ width: "220px" }, 300, () => {
          $("#leftPart li p").show(0)
          $("#leftPart div button:nth-child(2)").show(0)
          $("#leftPart div button:nth-child(3)").show(0)
        })
        $("#rightPart").animate({ width: `${w - 220}px` }, 300)
      }
      $("#leftPart li i").css("width", "40px")
      $("#leftPart li i").css("border-right", "solid #364150 1px")
      $("#leftPart div button:nth-child(1)").css("width", "33%")
      $("#leftPart img:nth-child(2)").hide(0)
      $("#leftPart img:nth-child(1)").show(0)
      $("#leftPart div").css("width", "100%")
      bios.cookie.set("menuID", true, 1)
      bios.menuID = true
    }
  },
  settings () {
    if (!bios.window) {
      const Window = React.createClass({
        getInitialState () {
          return {
            fName: "",
            sName: "",
            email: "",
            phone: "",
          }
        },
        componentDidMount () {
          const a = this
          s.emit("getUser", tmp)
          s.on("getUser", (data) => {
            if (a.isMounted()) {
              a.setState({
                fName: data.fName,
                sName: data.sName,
                email: data.email,
                phone: data.phone,
              })
            }
          })
        },
        render () {
          return (
                        <table className="setting" cellPadding="0" cellSpacing="0">
                            <tr><td>Imię:</td><td><input onChange={this.onTextChange} id="fName" type="text" value={this.state.fName}/></td></tr>
                            <tr><td>Nazwisko:</td><td><input onChange={this.onTextChange} id="sName" type="text" value={this.state.sName}/></td></tr>
                            <tr><td>Email:</td><td><input onChange={this.onTextChange} id="email" type="text" value={this.state.email}/></td></tr>
                            <tr><td>Telefon:</td><td><input onChange={this.onTextChange} id="phone" type="text" value={this.state.phone}/></td></tr>
                            <tr><td colSpan="2"><center><button onChange={this.onTextChange} onClick={this.saveData}>Zapisz</button></center></td></tr>
                        </table>
          )
        },
        onTextChange (e) {
          if (e.target.id == "fName") this.setState({ fName: e.target.value })
          if (e.target.id == "sName") this.setState({ sName: e.target.value })
          if (e.target.id == "email") this.setState({ email: e.target.value })
          if (e.target.id == "phone") this.setState({ phone: e.target.value })
        },
        saveData () {
          fName = document.getElementById("fName").value
          sName = document.getElementById("sName").value
          email = document.getElementById("email").value
          phone = document.getElementById("phone").value
          const dataToSend = {
            fName, sName, email, phone,
          }

          s.emit("updateUser", dataToSend)
          s.on("updateUser", (e) => {
            if (e) {
              msv(".window").loading.start()
              msv(".window").loading.action("img/ok.png", bios.renderMainView)
              bios.window = false
            } else {
              msv(".window").loading.start()
              msv(".window").loading.action("img/error.png")
            }
          })
        },
      })

      if (bios.cookie.get("module") && !bios.module) ReactDOM.render(<MainView moduleURL={bios.cookie.get("module")} window="hidden" windowName="Ustawienia" windowBody={React.createElement(Window, null)}/>, document.getElementById("body"))
      else ReactDOM.render(<MainView module={bios.module} window="hidden" windowName="Ustawienia" windowBody={React.createElement(Window, null)}/>, document.getElementById("body"))
      bios.window = true
    } else {
      bios.renderMainView()
      bios.window = false
    }
  },
  exit () {
    s.emit("logout", bios.cookie.get("_socket"))
    bios.cookie.delete("module")
  },
  module (e) {
    if (bios.module == this.state.modules[e]) {
      document.getElementById("rightPartLoading").style.display = "block"
      document.getElementById("iframe").src = bios.module.url
    } else if (bios.cookie.get("module") && bios.cookie.get("module").toString() == this.state.modules[e].url.toString()) {
      reloadPage = true
      bios.renderMainView()
    } else {
      bios.module = this.state.modules[e]
      bios.cookie.set("module", this.state.modules[e].url, 1)
      document.getElementById("rightPartLoading").style.display = "block"
      bios.renderMainView()
    }
  },
  reload () {
    // msv("#body").loading.start();
    // msv("#body").loading.stop(500);
    setTimeout(() => {
      reloadPage = true
      bios.renderMainView()
    }, 501)
  },
})
const RightPart = React.createClass({
  render () {
    let URL = ""
    if (this.props.module) URL = this.props.module.url
    if (bios.cookie.get("module")) URL = bios.cookie.get("module")
    if (this.props.moduleURL) URL = this.props.moduleURL
    return (<div id="rightPart"><iframe id="iframe" src={URL}></iframe></div>)
  },
})
const Window = React.createClass({
  render () {
    return (
            <div className={!this.props.window ? "hidden" : "window"} classID="window">
                <div className="sWTop">
                    <p>{this.props.windowName}</p>
                    <button title="Zamknąć okno" onClick={this.close}><i className="fa fa-times"/></button>
                </div>
                <div id="windowBody">{this.props.windowBody}</div>
            </div>
    )
  },
  close () {
    bios.window = false
    bios.renderMainView()
  },
})
const Timer = React.createClass({
  render () {
    const timerID = bios.timer.id
    return (
            <div className={!timerID ? "hidden" : "timer"}>
                <div>
                    <i className="fa fa-clock-o"></i>
                    <p>00:00:00</p>
                </div>
                <button onClick={this.off}>Zatrzymaj</button>
            </div>
    )
  },
  off (e) {
    s.emit("deleteTime")
    s.on("deleteTime", (data) => {
      if (data) bios.timer.off()
    })
  },
})
/* MAIN VIEW */


var bios = new function () {
  this.status = status === "true"
  this.menuID = true
  this.window = false
  this.module = ""
  this.modules = []

  this.start = function () {
    if (!this.status) {
      setInterval(bios.changeLoginBackground, 3000)
      ReactDOM.render(<LoginView/>, document.getElementById("body"))
    } else if (this.status) {
      bios.renderMainView()
      tmp2 = false
    }
  }
  this.makeMainView = function () {
    bios.renderMainView()
  }
  this.cookie = new function () {
    this.set = function (name, value, days) {
      if (days) {
        const date = new Date()
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000))
        var expires = `; expires=${date.toGMTString()}`
      } else var expires = ""
      document.cookie = `${name}=${value}${expires}; path=/`
    }
    this.get = function (name) {
      const nameEQ = `${name}=`
      const ca = document.cookie.split(";")
      for (let i = 0; i < ca.length; i++) {
        let c = ca[i]
        while (c.charAt(0) == " ") c = c.substring(1, c.length)
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length)
      }
      return null
    }
    this.delete = function (name) {
      this.set(name, "", -1)
    }
  }()
  this.renderMainView = function () {
    if (!reloadPage) {
      if (bios.module || bios.cookie.get("module")) {
        if (bios.module) {
          ReactDOM.render(<MainView module={bios.module}/>, document.getElementById("body"))
          if (document.getElementById("rightPartLoading")) document.getElementById("rightPartLoading").style.display = "block"
        } else if (bios.cookie.get("module")) {
          ReactDOM.render(<MainView moduleURL={bios.cookie.get("module")}/>, document.getElementById("body"))
          if (document.getElementById("rightPartLoading")) document.getElementById("rightPartLoading").style.display = "block"
        }
      } else {
        ReactDOM.render(<MainView moduleURL="/modules/dashboard/"/>, document.getElementById("body"))
        if (document.getElementById("rightPartLoading")) document.getElementById("rightPartLoading").style.display = "block"
      }
      if (bios.cookie.get("menuID") === "false") {
        $("#leftPart").animate({ width: "50px" }, 0)
        $("#rightPart").css("width", "calc(100% - 50px)")
        $("#leftPart li i").css("width", "50px")
        $("#leftPart li i").css("border", "0px")
        $("#leftPart li p").hide(0)
        $("#leftPart div button:nth-child(1)").css("width", "100%")
        $("#leftPart div button:nth-child(2)").hide(0)
        $("#leftPart div button:nth-child(3)").hide(0)
        $("#leftPart img:nth-child(1)").hide(0)
        $("#leftPart img:nth-child(2)").show(0)
        $("#leftPart div").css("width", "50px")
        this.menuID = false
      }
    } else {
      ReactDOM.unmountComponentAtNode(document.getElementById("body"))
      reloadPage = false
      if (bios.module || bios.cookie.get("module")) {
        if (bios.module) {
          ReactDOM.render(<MainView module={bios.module}/>, document.getElementById("body"))
          if (document.getElementById("rightPartLoading")) document.getElementById("rightPartLoading").style.display = "block"
        } else if (bios.cookie.get("module")) {
          ReactDOM.render(<MainView moduleURL={bios.cookie.get("module")}/>, document.getElementById("body"))
          if (document.getElementById("rightPartLoading")) document.getElementById("rightPartLoading").style.display = "block"
        }
      } else {
        ReactDOM.render(<MainView moduleURL="/modules/dashboard/"/>, document.getElementById("body"))
        if (document.getElementById("rightPartLoading")) document.getElementById("rightPartLoading").style.display = "block"
      }
      if (bios.cookie.get("menuID") === "false") {
        $("#leftPart").animate({ width: "50px" }, 0)
        $("#rightPart").css("width", "calc(100% - 50px)")
        $("#leftPart li i").css("width", "50px")
        $("#leftPart li i").css("border", "0px")
        $("#leftPart li p").hide(0)
        $("#leftPart div button:nth-child(1)").css("width", "100%")
        $("#leftPart div button:nth-child(2)").hide(0)
        $("#leftPart div button:nth-child(3)").hide(0)
        $("#leftPart img:nth-child(1)").hide(0)
        $("#leftPart img:nth-child(2)").show(0)
        $("#leftPart div").css("width", "50px")
        this.menuID = false
      }
    }
  }
  this.timer = new function () {
    this.id = false
    this.sTime = 0
    this.on = function (sTime) {
      bios.timer.sTime = sTime
      bios.timer.interval = setInterval(bios.timer.timerF, 1000)
      bios.timer.id = true
      bios.renderMainView()
    }
    this.off = function () {
      clearInterval(bios.timer.interval)
      bios.timer.id = false
      bios.renderMainView()
    }
    this.timerF = function (e) {
      const time0 = bios.timer.sTime

      let hour = new Date(Date.now()).getHours() - new Date(time0).getHours()
      let min = new Date(Date.now() - time0).getMinutes()
      let sec = new Date(Date.now() - time0).getSeconds()

      if (hour >= 0 && hour < 10) hour = `0${hour}`
      if (min >= 0 && min < 10) min = `0${min}`
      if (sec >= 0 && sec < 10) sec = `0${sec}`

      const time = `${hour}:${min}:${sec}`
      $(".timer").find("p")[0].innerHTML = time
    }
  }()
  this.changeLoginBackground = function () {
    if ($("#loginTable").is(":visible")) {
      $(".loginTable").css("background", "#777777")

      if (backgroundImage == 1) {
        $(`#loginTableBackground${backgroundImage}`).fadeOut(300, () => {
          $("#loginTableBackground2").fadeIn(200)
        })
      } else if (backgroundImage == 2) {
        $(`#loginTableBackground${backgroundImage}`).fadeOut(300, () => {
          $("#loginTableBackground3").fadeIn(200)
        })
      } else if (backgroundImage == 3) {
        $(`#loginTableBackground${backgroundImage}`).fadeOut(300, () => {
          $("#loginTableBackground4").fadeIn(200)
        })
      } else if (backgroundImage == 4) {
        $(`#loginTableBackground${backgroundImage}`).fadeOut(300, () => {
          $("#loginTableBackground1").fadeIn(200)
          backgroundImage = 1
        })
      }

      backgroundImage++
    }
  }
}()


s.on("connect", () => {
  bios.start()
  s.on("authorization", (e) => {
    if (e) {
      bios.cookie.set("_auth", e, 1)
      msv(".loginBlock").loading.action("img/ok.png", bios.makeMainView)
      setTimeout(() => {
        location.reload()
      }, 100)
    } else if (!e || !tmp2) {
      setTimeout(() => {
        msv(".loginBlock").loading.action("img/error.png")
        setTimeout(() => {
          location.reload()
        }, 100)
      }, 500)
    }
  })
  s.on("logout", (e) => {
    if (e) {
      bios.cookie.delete("_auth")
      setTimeout(() => {
        location.reload()
      }, 100)
    }
  })
  s.on("RELOAD", (e) => {
    if (e) {
      bios.status = false
      bios.start()
    }
  })
  s.on("updateBecauseRestartServer", (e) => {
    bios.status = false
    bios.start()
    bios.cookie.delete("_auth")
  })
})
window.addEventListener("message", (e) => {
  const data0 = e.data
  const d0 = e.source.location.pathname

  if (data0 == "loaded") document.getElementById("rightPartLoading").style.display = "none"
  if (data0 == "startTimer") {
    var d = new Date()
    const n = d.getTime()
    bios.timer.on(n)
  }
  if (data0 == "stopTimer") bios.timer.off()
  if (~data0.indexOf("openProjectOne")) {
    var d = data0.split("?")
    d = d[1]
    bios.cookie.set("projektID", d, 1)
    i = 0
    do {
      var e = bios.modules[i]
      if (e.name == "Projekty") {
        bios.module = e
        bios.cookie.set("module", e.url, 1)
        document.getElementById("rightPartLoading").style.display = "block"
        bios.renderMainView()
        break
      }
    } while (i++ <= bios.modules.length - 2)
  }
})
$(document).keypress((e) => {
  if (e.which === 13 && !bios.status) {
    tmp = `${Math.floor((Math.random() * 100000000000) + 1000000000)}_tmp`
    s.emit("authorize", { l: document.getElementById("login").value, p: document.getElementById("password").value, id: tmp })
    msv().loading.params("#dddddd", "img/loading.gif", 0.6)
    msv(".loginBlock").loading.start()
  }
})
