import React, { Component } from "react";
import { Link,Switch } from "react-router-dom";
import cookie from 'react-cookies'
import Routermain from "./routermain";

class App extends Component {
  constructor(props) {
    console.log("window.location", window.location);

    let tempname = window.location.search;
    console.log("tempname", tempname);
    super(props);
    this.state = {
      load: false,
      tempname: tempname,
      redirection: false
    };
  }
  
  componentDidMount() {
    let cname = [];
    let is_redirect = false;

    let tempname = this.state.tempname;
    console.log("tempname", tempname);
    if (tempname !== "") {
      console.log("tempname", tempname);

      let searchContest = [];
      let shareContest = [];
      cname = tempname.split("/");
      console.log("cname[0][1]", cname);

      shareContest = cname[2].split("=");

      if (shareContest[0] === "refered_by_id") {
        console.log("refered_by_id");
        localStorage.setItem("refered_contest_id", cname[1]);
        localStorage.setItem("refered_by_id", shareContest[1]);
        cookie.save('refered_contest_id', cname[1], { path: '/' })
        cookie.save('refered_by_id', shareContest[1], { path: '/' })
        is_redirect = true;
        this.setState({
          contest_id: cname[1],
          load: true,
          redirection: is_redirect
        });
      } else if (cname[0] === "?Contest") {
        // if()
        searchContest = cname[3].split("=");
        console.log("earchContest[1]", searchContest[1]);
        is_redirect = true;
        this.setState({
          contest_id: cname[1],
          load: true,
          redirection: is_redirect
        });
        localStorage.setItem("check_user_id", cname[2]);
        localStorage.setItem("refered_contest_id", cname[1]);
        localStorage.setItem("refered_by_id", searchContest[1]);
        cookie.save('refered_by_id', searchContest[1], { path: '/' })
        cookie.save("refered_contest_id", cname[1], { path: '/' })
        cookie.save("check_user_id", cname[2], { path: '/' })
        console.log("check_user_id", cookie.load("check_user_id"));
        console.log(
          "refered_contest_id",
          cookie.load("refered_contest_id")
        );
        console.log("refered_by_id", cookie.load("refered_by_id"));

        console.log("this.state", this.state);
      }
    }
    else {
      this.setState({
        load: true,
        redirection: is_redirect
      });
    }
    console.log("cname", cname);
  }

  render() {
    return (
      <div>
        {this.state.load && (
          <div>
            {!this.state.redirection && <Link to="/" />}
            {this.state.redirection && (
              <Link to="/Contest/6/email|5b20a84aa6803a91915c8f99" />
            )}
            <Routermain />
          </div>
        )}
      </div>
    );
  }
}

export default App;
