package edu.neusoft.project.controller;

import edu.neusoft.project.model.service.IndentService;
import edu.neusoft.project.model.service.PersonService;
import edu.neusoft.project.model.service.SongService;
import edu.neusoft.project.model.vo.*;
import edu.neusoft.project.util.CSVReader;
import edu.neusoft.project.util.MyMD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.HashSet;
import java.util.List;




@Controller
public class MusicBasicAction {
    @Autowired
    private PersonService service;
    @Autowired
    private SongService songService;
    @Autowired
    private IndentService indentService;

    String eventsName="";
    private MyMD5Util myMD5Util = new MyMD5Util();


//    private Person globalPerson = null;
//    HttpSession session;
    public String level = null;



    @RequestMapping("userLogin.action")
    public String adminList(){
        return "userLogin";
    }
    @RequestMapping("login.action")
    public String login(){
        return "userLogin";
    }
    /*public ModelAndView login(){
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.setViewName("login");
        return modelAndView;
    }*/
//    直接返回String，就相当于创建ModelAndView，viewName
//    @RequestMapping("regist.action")
//    public String regist(){
//        return "regist";
//    }

    @RequestMapping("userRegist.action")
    public String registUser(){
        return "userRegist";
    }

    @RequestMapping("loginSuccess.action")
    public String loginSuccess(HttpServletRequest request, ModelMap model){
        Person person = new Person();
        Person ret= new Person();
        String excl = "";
        HttpSession sessions = request.getSession();
//        HttpServletRequest request,
        service.insLineCount();

        //post Username loginName
        //              searchedPersonToken
        String searchedPersonToken=(String) sessions.getAttribute("searchedPersonToken");
        String loginName=(String) sessions.getAttribute("loginName");
        String searchedPersonCode=(String) sessions.getAttribute("searchedPersonCode");
        person.setToken(searchedPersonToken);
        person.setUsername(loginName);
        person.setPersonCode(searchedPersonCode);

        //userToken
        String userToken=(String)sessions.getAttribute("userToken");
        System.out.println("loginSuccessed.userToken----"+userToken);
        //save eventsName
        eventsName = person.getUsername();
        sessions.setAttribute("eventName",eventsName);
        if (userToken.equals(searchedPersonToken)){
            excl = String.valueOf(person.getUsername().charAt(0));

            if (excl.equals("!")){
                person.setUsername(person.getUsername().substring(1));
                ret=service.adminLogin(person.getUsername(),userToken);
            }else {
                ret = service.login(person.getUsername(),userToken);
            }
        }
        //rebuild username

        //set login-person in session
        sessions.setAttribute("loginedPer",person);
        Person loginedPer= new Person();
        loginedPer= (Person) sessions.getAttribute("loginedPer");
        System.out.println(loginedPer);
        System.out.println("----------------------");
        //check user category <!-admin;""-user>
        if (excl.equals("!") ){   //AdminManage
            System.out.println("equals !=========");
            if ( ret != null) {
                List<Indent> indents = service.showAllAdminIndent();
                System.out.println(indents);
                model.put("adminName", person.getUsername());
                model.put("AllIndents", indents);
                int tradeCount = service.getTradingCount();
                model.put("tradeCount",tradeCount);
                return "adminIndentList";
            }else if ( ret == null){ //failed
                return "userLogin";
            }
        }else  if (loginedPer!=null){ //normal user
            //check user Token

//            String uT=myMD5Util.encryptUserToken(loginedPer.getUsername(),loginedPer.getPassword()).toUpperCase(); //calc uT
            String getUT=service.getUserToken(loginedPer.getPersonCode());
            System.out.println("searchedPersonToken/userToken:-- "+searchedPersonToken+"/"+userToken);
            if (!userToken.toUpperCase().equals(searchedPersonToken)){  //checked failed
                eventsName = "";
                sessions.removeAttribute("eventName");
                sessions.removeAttribute("loginedPer");
                sessions.removeAttribute("userToken");
                return "Homepage";
            }
            System.out.println("case:userToken/getUT-----"+userToken.toUpperCase()+"/"+getUT);
            if (!userToken.toUpperCase().equals(getUT)){
                eventsName = "";
                sessions.removeAttribute("eventName");
                sessions.removeAttribute("loginedPer");
                sessions.removeAttribute("userToken");
                return "userLogin";
            }
//          service.updUserToken(loginedPer.getPersonCode(),userToken);   //move to regist

            //update UserSession
            service.updUserSession(loginedPer);
            //user level
            String level = service.getLevel(person);
            //get possible likes
            List<Song> list = songService.likeSongs();
            System.out.println(ret);
            if(ret!=null){
                //user login succeed
                model.put("list",list);
                model.put("username",loginedPer.getUsername());
                model.put("password",loginedPer.getPassword());
                model.put("personCode",loginedPer.getPersonCode());
                model.put("personLevel",level);
                model.put("personListened",loginedPer.getPersonListened());
                return "logined";
            }
        }
        //failed to user login
        return "userLogin";
    }

    @RequestMapping("registSuccess.action")
    public String registSuccess(HttpServletRequest request,Person person, ModelMap model){
        Date date = new Date();
        String d = "#"+String.valueOf(date.getTime());
        person.setPersonCode(d);
        service.regist(person);
        HttpSession sessions = request.getSession();
        String userToken=(String)sessions.getAttribute("userRegistToken");
        service.updUserToken(person.getPersonCode(),userToken);
        System.out.println(service.getUserToken(person.getPersonCode()));
        return "userLogin";
    }

    @RequestMapping("registWithUT.action")
    @ResponseBody
    public int registWithUT(HttpServletRequest request,String userToken){
        int status = 0;
        System.out.println("StringRegist userToken:---------"+userToken);

        if (!userToken.equals("")){
            if (!userToken.equals("BECAC6071D247E0D11DD9225157E24CF")){
                if (!userToken.equals("becac6071d247e0d11dd9225157e24cf")){
                    HttpSession sessions = request.getSession();
                    sessions.setAttribute("userRegistToken",userToken);
//                    String userToken=(String)sessions.getAttribute("userToken");

                    status = 1;
                }
            }
        }

        return status;
    }

    @RequestMapping("postUsername.action")
    @ResponseBody
    public int postUsername(String username,HttpSession sessions){

        System.out.println("String username:---------"+username);

        if (!username.equals("")){
            sessions.setAttribute("loginName",username);
            Person person =new Person();
            String excl = String.valueOf(username.charAt(0));
            if (excl.equals("!")){
                String adminName=username.substring(1);
//                person.setUsername(person.getUsername().substring(1));
                person=service.selUserByAdminName(adminName);
                sessions.setAttribute("searchedPersonCode",person.getPersonCode());
                sessions.setAttribute("searchedPersonToken",person.getToken());
                System.out.println("postUsername------"+sessions.getAttribute("loginName"));
                System.out.println("searchedPersonCode------"+sessions.getAttribute("searchedPersonCode"));
                System.out.println("searchedPersonToken------"+sessions.getAttribute("searchedPersonToken"));
            }else if (!excl.equals("!")){
                person=service.selUserByName(username);
                sessions.setAttribute("searchedPersonCode",person.getPersonCode());
                sessions.setAttribute("searchedPersonToken",person.getToken());
                System.out.println("postUsername------"+sessions.getAttribute("loginName"));
                System.out.println("searchedPersonCode------"+sessions.getAttribute("searchedPersonCode"));
                System.out.println("searchedPersonToken------"+sessions.getAttribute("searchedPersonToken"));
            }



        }

        return 1;
    }


    @RequestMapping("loginWithUT.action")
    @ResponseBody
    public int loginWithUT(String userToken,HttpSession sessions){
        int status = 0;
        System.out.println("String userToken:---------"+userToken);
        sessions.setAttribute("userToken",userToken);
        if (!userToken.equals("")){
            if (!userToken.equals("BECAC6071D247E0D11DD9225157E24CF")){
                if (!userToken.equals("becac6071d247e0d11dd9225157e24cf")){
                    sessions.setAttribute("userToken",userToken);
                    System.out.println("ut------"+sessions.getAttribute("userToken"));
                    status = 1;
                }
            }
        }

        return status;
    }


    @RequestMapping("Homepage.action")
    public String homepage(ModelMap model,HttpSession sessions) {
        System.out.println("System Load Okay!--------------");
        //////////////////////////////////////////////
        if (eventsName==null){
            eventsName="";
        }
        if (eventsName.equals("")) {
            return "Homepage";
        } else if (!eventsName.equals("")) {
            String eventName = (String) sessions.getAttribute("eventName");
            if (eventName == null) {
                eventsName = "";
                sessions.removeAttribute("eventName");
                sessions.removeAttribute("loginedPer");
                return "Homepage";
            }
            Person ret = new Person();
            Person loginedPer = new Person();
            loginedPer = (Person) sessions.getAttribute("loginedPer");
            loginedPer.setUsername(eventName);
            String sessionStr = service.getUserSession(loginedPer.getPersonCode());//get UserSession(32) --> str
            String md5UtilStr = myMD5Util.encryptUserSession(loginedPer.getUsername(), loginedPer.getPassword());
            //
            if (!sessionStr.equals(md5UtilStr)) {        //overDDL
                System.out.println("Homepage--overDDL---------" + loginedPer);
                eventsName = "";
                sessions.removeAttribute("eventName");
                sessions.removeAttribute("loginedPer");
                return "Homepage";
            }
            System.out.println("Homepage-----------" + loginedPer);
            service.resetUserSession(loginedPer.getPersonCode());

            if (String.valueOf(eventName.charAt(0)).equals("!")) {
                loginedPer.setUsername(loginedPer.getUsername().substring(1));
                ret = service.adminLogin(loginedPer.getUsername(), loginedPer.getToken());
                if (ret != null) {
                    List<Indent> indents = service.showAllAdminIndent();
                    System.out.println(indents);
                    model.put("adminName", loginedPer.getUsername());
                    model.put("AllIndents", indents);

                    int tradeCount = service.getTradingCount();
                    model.put("tradeCount",tradeCount);
                    return "adminIndentList";
                } else if (ret == null) {
                    return "Homepage";
                }
            } else {
                ret = service.login(loginedPer.getUsername(), loginedPer.getToken());
                if (loginedPer != null) {
                    String level = service.getLevel(loginedPer);
                    List<Song> list = songService.likeSongs();
                    if (ret != null) {
                        service.updUserSession(loginedPer);
                        model.put("list", list);
                        model.put("username", loginedPer.getUsername());
                        model.put("password", loginedPer.getPassword());
                        model.put("personCode", loginedPer.getPersonCode());
                        model.put("personLevel", level);
                        model.put("personListened", loginedPer.getPersonListened());
                        return "logined";
                    }
                }
            }
        }
        return "Homepage";
    }

    @RequestMapping("logo.action")
    public String logo(ModelMap model,HttpSession sessions){
        Person loginedPer= new Person();
        loginedPer= (Person) sessions.getAttribute("loginedPer");
        if (loginedPer != null){
            List<Song> list02 = songService.likeSongs();
            model.put("list",list02);
            model.put("username",loginedPer.getUsername());
            model.put("password",loginedPer.getPassword());
            model.put("personCode",loginedPer.getPersonCode());
            model.put("personLevel",level);
            model.put("personListened",loginedPer.getPersonListened());
            return "logined";
        }
        return "Homepage";
    }
    @RequestMapping("StationAnalysis.action")
    public String stationAnalysis(ModelMap model,HttpSession session){
        Person loginedPer= new Person();
        loginedPer= (Person) session.getAttribute("loginedPer");
        List<AckTime> ackList=service.getAckTime();
        int ack1 = 0,ack2= 0,ack3= 0,ack4= 0,ack5= 0;
        ack1=ackList.get(0).getNum();
        ack2=ackList.get(1).getNum();
        ack3=ackList.get(2).getNum();
        ack4=ackList.get(3).getNum();
        ack5=ackList.get(4).getNum();
//        ServletContext context = session.getServletContext();
        int lineCount=service.readLineCount();

        model.put("lineCount",lineCount);
        model.put("ack1",ack1);
        model.put("ack2",ack2);
        model.put("ack3",ack3);
        model.put("ack4",ack4);
        model.put("ack5",ack5);

        CSVReader reader= new CSVReader("V:\\WorkSpaces\\JavaEEStructure\\DataCollector01.csv");
        Monite m =null;
        try {
            m=reader.getElementLine();
            System.out.println(m.toString());

        } catch (IOException e) {
            e.printStackTrace();
        }
        model.put("adminName",loginedPer.getUsername());
        model.put("monite",m);
        return "stationAnalysis";
    }
    @RequestMapping("mapEcharts.action")
    public String mapEcharts(HttpSession sessions,ModelMap model){
        Person loginedPer= new Person();
        loginedPer= (Person) sessions.getAttribute("loginedPer");
        model.put("adminName",loginedPer.getUsername());
        return "echarts/mapMain";
    }
    @RequestMapping("web.action")
    public String web(){
        return "AckTime";
    }

    @RequestMapping("aboutMe.action")
    public String aboutMe(ModelMap model,HttpSession sessions){
        System.out.println("AboutMeAction");
        Person loginedPer= new Person();
        loginedPer= (Person) sessions.getAttribute("loginedPer");

        List<Indent> indentList = indentService.showMyIndentList(loginedPer.getPersonCode());
        System.out.println(indentList);
//        model.put("myIndent",indentList);


        if (loginedPer!=null){
            List<Song> list04 = songService.likeSongs();
            model.put("list",list04);
            model.put("username",loginedPer.getUsername());
            model.put("password",loginedPer.getPassword());
            model.put("personCode",loginedPer.getPersonCode());
            model.put("personLevel",level);
            model.put("personListened",loginedPer.getPersonListened());
            model.put("myIndent",indentList);
            return "aboutMe";
        }
        return "Homepage";

    }
    @RequestMapping("findMusic.action")
    public String findMusic(ModelMap model,HttpSession sessions){
        Person loginedPer= new Person();
        loginedPer= (Person) sessions.getAttribute("loginedPer");
        if (loginedPer!=null){
            List<Song> list04 = songService.likeSongs();
            model.put("list",list04);
            model.put("username",loginedPer.getUsername());
            model.put("password",loginedPer.getPassword());
            model.put("personCode",loginedPer.getPersonCode());
            model.put("personLevel",level);
            model.put("personListened",loginedPer.getPersonListened());
            return "logined";
        }
        return "Homepage";
    }

    @RequestMapping("myMusic.action")
    public String myMusic(ModelMap model,HttpSession sessions){
        Person loginedPer= new Person();
        loginedPer= (Person) sessions.getAttribute("loginedPer");
        if (loginedPer!=null){
            List<Song> list02 = songService.likeSongs();
            model.put("list",list02);
            List<Song> mySong = songService.mySong(loginedPer.getPersonCode());
            System.out.println(mySong+String.valueOf(Math.random()));
            model.put("mySong",mySong);

            model.put("username",loginedPer.getUsername());
            model.put("password",loginedPer.getPassword());
            model.put("personCode",loginedPer.getPersonCode());
            model.put("personLevel",level);
            model.put("personListened",loginedPer.getPersonListened());
            return "loginedAndMyMusic";
        }
        return "Homepage";
    }

    @RequestMapping("myFriends.action")
    public String myFriends(ModelMap model,HttpSession sessions){
        Person loginedPer= new Person();
        loginedPer= (Person) sessions.getAttribute("loginedPer");
        if (loginedPer!=null){
            List<Song> list04 = songService.likeSongs();
            model.put("list",list04);
            model.put("username",loginedPer.getUsername());
            model.put("password",loginedPer.getPassword());
            model.put("personCode",loginedPer.getPersonCode());
            model.put("personLevel",level);
            model.put("personListened",loginedPer.getPersonListened());
            return "logined";
        }
        return "Homepage";
    }

    @RequestMapping("searchSongs.action")
    public String searchSongs(String searchText,ModelMap model,HttpSession sessions){
        Person loginedPer= new Person();
        loginedPer= (Person) sessions.getAttribute("loginedPer");
//        System.out.println(searchText+"0000000000000000");
        if (searchText.equals("")||searchText==null){
            if (loginedPer!=null){
                List<Song> list04 = songService.likeSongs();
                model.put("list",list04);
                model.put("username",loginedPer.getUsername());
                model.put("password",loginedPer.getPassword());
                model.put("personCode",loginedPer.getPersonCode());
                model.put("personLevel",level);
                model.put("personListened",loginedPer.getPersonListened());
                System.out.println();
                return "logined";
            }
            return "Homepage";
        }
        Song song;
        String sharp = String.valueOf(searchText.charAt(0));
        if (sharp.equals("#")){
            //search song by id
//            System.out.println("true");
//            System.out.println(searchText.charAt(0));
            searchText=searchText.substring(1);
            song=songService.selBySongId(searchText);
        }else {
            //search song by name
//            System.out.println("false");
//            System.out.println(searchText);
            song = songService.selBySongName(searchText);

        }
        System.out.println(searchText);
        System.out.println(song);
        //likes
        List<Song> list = songService.likeSongs();
        //putModel
        if (song!=null){
            model.put("searchedSong", song);
//            model.put("searchedSongid",song.getId());
        }else {
            model.put("searchedSong", "");
            model.put("searchedSongid","");
        }
        model.put("list",list);
        //print likes
//        System.out.println(list);



            if(loginedPer!=null){
                songService.addListened(loginedPer);
                model.put("username",loginedPer.getUsername());
                model.put("password",loginedPer.getPassword());
                model.put("personCode",loginedPer.getPersonCode());
                model.put("personLevel",level);
                model.put("personListened",loginedPer.getPersonListened());
                System.out.println("loginedPer---------"+loginedPer);
                return "logined";

            }

        return "searchedButNotLogined";
    }

    @RequestMapping("likes.action")
    public void likeSongs(ModelMap model){
//        System.out.println("model:"+ model);
        List<Song> list = songService.likeSongs();
        model.put("list",list);

    }

//    @RequestMapping("shareAct.action")
//    @ResponseBody
//    public int shareAct(String id,HttpSession sessions){
//        Person loginedPer= new Person();
//        loginedPer= (Person) sessions.getAttribute("loginedPer");
//        int status= songService.likeAct(id,loginedPer.getPersonCode());
//        System.out.println(status);
//        return status;
//    }
    @RequestMapping("likeAct.action")
    @ResponseBody
    public int likeAct(String id,HttpSession sessions){
        Person loginedPer= new Person();
        loginedPer= (Person) sessions.getAttribute("loginedPer");
        int status= songService.likeAct(id,loginedPer.getPersonCode());
        System.out.println(status);
        return status;
    }
    @RequestMapping("unlikeAct.action")
    @ResponseBody
    public int unlikeAct(String id,HttpSession sessions){
        Person loginedPer= new Person();
        loginedPer= (Person) sessions.getAttribute("loginedPer");
        int status= songService.unlikeAct(id,loginedPer.getPersonCode());
        System.out.println(status+"---------unlikeAct");
        return status;
    }
    @RequestMapping("buyAct.action")
    @ResponseBody
    public int buyAct(String id,HttpSession sessions){
        Person loginedPer= new Person();
        loginedPer= (Person) sessions.getAttribute("loginedPer");
        int status = service.buySong(id,loginedPer.getPersonCode());
        System.out.println(status +"--------------buy");
        return status;
    }


    @RequestMapping("indent.action")
    public String indentList(ModelMap model,HttpSession sessions){
        Person loginedPer= new Person();
        loginedPer= (Person) sessions.getAttribute("loginedPer");

        List<Indent> indents=service.showAllAdminIndent();
        System.out.println(indents);
        System.out.println(loginedPer);
        model.put("adminName",loginedPer.getUsername());
        model.put("AllIndents",indents);
        int tradeCount = service.getTradingCount();
        model.put("tradeCount",tradeCount);
        return "adminIndentList";
    }
    @RequestMapping("user.action")
    public String userList(ModelMap model,HttpSession sessions){
        Person loginedPer= new Person();
        loginedPer= (Person) sessions.getAttribute("loginedPer");

        List<Person> users=service.showAllAdminUser();
        System.out.println(users);
        System.out.println(loginedPer);
        model.put("adminName",loginedPer.getUsername());
        model.put("AllUsers",users);
        return "adminUserList";
    }

    @RequestMapping("logOut.action")
    public String logOut(HttpSession sessions){
        service.remLineCount();
        Person loginedPer= new Person();
        loginedPer= (Person) sessions.getAttribute("loginedPer");
        service.resetUserSession(loginedPer.getPersonCode());
        sessions.removeAttribute("userToken");
        loginedPer = null;
        sessions.setAttribute("loginedPer",loginedPer);
//
//        ServletContext context = sessions.getServletContext();
//        int lineCount = (Integer) context.getAttribute("lineCount");
//        context.setAttribute("lineCount", lineCount - 1);
//        HashSet<HttpSession> sessionSet = (HashSet<HttpSession>) context.getAttribute("sessionSet");
//        if(sessionSet!=null){
//            sessionSet.remove(sessions);
//        }

        return "Homepage";
    }








//    @RequestMapping("person.action")
//    public String person(Model model){
////        到数据库查询所有的数据，传递到前台，跳转界面
//        List<Person> list=service.showAll();
//        model.addAttribute("list",list);
//        return "person";
//    }
//
////    使用String/ModelAndView作为返回值，表示返回界面
////    使用void/String/List等形式作为返回值，表示返回的是数据，
////    需要使用@ResponseBody把返回值作为json数据格式传递
//    @ResponseBody
//    @RequestMapping("deletePerson.action")
//    public void deletePerson(String username){
//        System.out.println("--------deletePerson.action");
//        service.deleteByName(username);
////        return null;
//    }
//    @ResponseBody
//    @RequestMapping("updatePerson.action")
//    public void updatePerson(String username,String Nusername){
//        System.out.println("--------deletePerson.action");
//        service.updateByName(username,Nusername);
////        return null;
//    }
}
