package web

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"task"
	"time"
	. "tools"
)

// TASK
func Main(w http.ResponseWriter, r *http.Request) {
	defer Catch()
	if CheckSession(w, r) {
		ss, _ := Store.Get(r, SN)
		data := map[string]interface{}{"s_name": ss.Values["s_name"]}
		//查询配置规则
		res, _ := MgoClass.Find(COLL_TASK, nil, `{"_id":-1}`, nil, false, 0, 200)
		for _, r := range *res {
			if r["s_starttime"] == nil || r["s_starttime"] == int64(0) {
				r["s_starttime"] = ""
			} else {
				strtime := time.Unix(r["s_starttime"].(int64), 0).Format("2006-01-02 15:04:05")
				r["s_starttime"] = strtime

			}
		}
		data["task"] = res
		ExecuteTpl("main.html", &data, w)
	} else {
		http.Redirect(w, r, "/", http.StatusFound)
	}
}

// TASK-SAVE
func Save(w http.ResponseWriter, r *http.Request) {
	defer Catch()
	res := JSON{}
	if CheckSession(w, r) {
		_id := r.FormValue("_id")
		val := GetVal(r)
		//		prerule := val["s_prerule"].(string)
		//		prerule = regexp.MustCompile("\\n|\\s+").ReplaceAllString(prerule, ",")
		//		s_prerule := strings.Split(prerule, ",")
		//		log.Println("---------", s_prerule)

		val["l_lasttime"] = time.Now().Unix()
		if _id == "" {
			session, _ := Store.Get(r, SN)
			val["i_status"] = 0
			val["s_use"] = session.Values["s_name"]
			val["l_date"] = time.Now().Unix()
			val["s_starttime"] = int64(0)
			ids := MgoClass.Save(COLL_TASK, val)
			if ids != "" {
				//task.TaskMap = map[string]*task.TTask{}
				//go task.InitRule() //重新初始化任务
				res.Status = true
				res.Msg = "保存成功"
			} else {
				res.Msg = "保存失败"
			}
		} else {
			if val["s_starttime"] == "" {
				val["s_starttime"] = int64(0)
			} else {
				nowtime, _ := time.ParseInLocation("2006-01-02 15:04:05", val["s_starttime"].(string), time.Local)
				val["s_starttime"] = nowtime.Unix()
			}

			b := MgoClass.Update(COLL_TASK, `{"_id":"`+_id+`"}`, map[string]interface{}{
				"$set": val,
			}, false, false)
			if b {
				//task.TaskMap = map[string]*task.TTask{}
				//go task.InitRule() //重新初始化任务
				res.Status = true
				res.Msg = "保存成功"
			} else {
				res.Msg = "保存失败"
			}
		}
	} else {
		res.Msg = "重新登陆"
	}
	WriteJSON(w, &res)
}

func DDelete(w http.ResponseWriter, r *http.Request) {
	defer Catch()
	res := JSON{}
	if CheckSession(w, r) {
		_id := r.FormValue("_id")
		if _id == "" {
			res.Msg = "id不能为空"
		} else {
			task.TaskLock.Lock()
			defer task.TaskLock.Unlock()
			tt := task.NEWTASKPOOL[_id]
			if tt != nil {
				tt.SStop()
				delete(task.NEWTASKPOOL, _id)
				tt = nil
			}
			b := MgoClass.Del(COLL_TASK, `{"_id":"`+_id+`"}`)
			if b {
				//go task.InitRule() //重新初始化任务
				res.Status = true
				res.Msg = "删除成功"
			} else {
				res.Msg = "删除失败"
			}
		}
	} else {
		res.Msg = "重新登陆"
	}
	WriteJSON(w, res)
}

// 更新任务状态
func UpdateTaskStatus(id string, status int) bool {
	return MgoClass.Update(COLL_TASK, `{"_id":"`+id+`"}`, &map[string]interface{}{
		"$set": map[string]interface{}{
			"i_status": status,
		},
	}, false, false)
}

// UpdateTaskRule 更新任务规则
func UpdateTaskRule(w http.ResponseWriter, r *http.Request) {
	defer Catch()
	res := JSON{}
	tid := r.FormValue("_id")
	b := task.UpdateTaskInfo(true, tid)
	log.Println("taskid:", tid, "update rule", b)
	if b {
		if t := task.NEWTASKPOOL[tid]; t != nil {
			t.B_UpdateRule = true
		}
		res.Msg = "更新成功"
		res.Status = true
	} else {
		res.Msg = "更新规则失败"
	}
	WriteJSON(w, res)
}

// TASK-RUN
func TTRun(w http.ResponseWriter, r *http.Request) {
	defer Catch()
	res := JSON{}
	if CheckSession(w, r) {
		_id := r.FormValue("_id")
		if _id == "" {
			res.Msg = "_id不能为空"
		} else {
			task.TaskLock.Lock()
			defer task.TaskLock.Unlock()
			tt := task.NEWTASKPOOL[_id]
			if tt != nil {
				log.Println("---pause to run", _id)
				//从暂停到启动
				if tt.I_status == 0 {
					tt.I_status = 1
					if UpdateTaskStatus(_id, 1) {
						res.Status = true
						go tt.RRun()
					} else {
						res.Msg = "更新任务失败.."
					}
				} else {
					res.Status = false
					res.Msg = "请先停止任务"
				}
			} else {
				log.Println("---stop to run", _id)
				//从停止到启动
				if UpdateTaskStatus(_id, 1) {
					task.NewLoadTask(_id, &res) //加载任务
				} else {
					res.Msg = "更新任务失败.."
				}
			}
		}
	} else {
		res.Msg = "重新登陆"
	}
	WriteJSON(w, res)
}

func TTStop(w http.ResponseWriter, r *http.Request) {
	defer Catch()
	res := JSON{}
	if CheckSession(w, r) {
		_id := r.FormValue("_id")
		if _id == "" {
			res.Msg = "_id不能为空"
		} else {
			if UpdateTaskStatus(_id, 0) {
				task.TaskLock.Lock()
				defer task.TaskLock.Unlock()
				tt := task.NEWTASKPOOL[_id]
				if tt != nil {
					tt.I_status = 1
					go tt.SStop()
					delete(task.NEWTASKPOOL, _id)
					if ControlTaskRun { //线上环境
						AllTaskFinish = true //关闭任务时，设置所有任务已完成，满足下次启动时可以启动
					}
					res.Data = tt.Sstatus()
					res.Msg = "已停止.."
					res.Status = true
				} else {
					res.Msg = "任务并没有启动.."
				}
			} else {
				res.Msg = "更新任务失败.."
			}
		}
	} else {
		res.Msg = "重新登陆"
	}
	WriteJSON(w, res)
}

// 暂停任务
func TTPause(w http.ResponseWriter, r *http.Request) {
	defer Catch()
	res := JSON{}
	if CheckSession(w, r) {
		_id := r.FormValue("_id")
		if _id == "" {
			res.Msg = "_id不能为空"
		} else {
			if UpdateTaskStatus(_id, 0) {
				task.TaskLock.Lock()
				defer task.TaskLock.Unlock()
				tt := task.NEWTASKPOOL[_id]
				if tt != nil {
					tt.SStop()
					res.Data = tt.Sstatus()
					res.Msg = "已暂停.."
					res.Status = true
				} else {
					res.Msg = "任务并没有启动.."
				}
			} else {
				res.Msg = "更新任务失败.."
			}
		}
	} else {
		res.Msg = "重新登陆"
	}
	WriteJSON(w, res)
}

// 测试action
func TTset(w http.ResponseWriter, r *http.Request) {
	defer Catch()
	res := JSON{}
	if CheckSession(w, r) {
		_id := r.FormValue("_id")
		if _id == "" {
			res.Msg = "_id不能为空"
		} else {
			s_mgourl := r.FormValue("s_mgourl")
			s_mgodb := r.FormValue("s_mgodb")
			s_coll := r.FormValue("s_coll")
			i_poolsize := r.FormValue("i_poolsize")
			s_startid := r.FormValue("s_startid")
			s_endid := r.FormValue("s_endid")
			s_query := r.FormValue("s_query")

			log.Println("---Test to run", _id)
			//从停止到启动
			//用到规则-数据库连接-等可用信息
			bs, filename := task.NewLoadTestTask(_id, s_mgourl, s_mgodb, s_coll, i_poolsize, s_startid, s_endid, s_query)
			res.Status = bs
			res.Data = filename
		}
	} else {
		res.Msg = "重新登陆"
	}
	WriteJSON(w, res)
}

func updatestatus(w http.ResponseWriter, r *http.Request) {
	defer Catch()
	res := JSON{}
	if CheckSession(w, r) {
		id := r.FormValue("id")
		if id == "" {
			res.Msg = "id不能为空"
		} else {
			res.Status = true
			res.Data = task.UPDATE.Get(id)
		}
	} else {
		res.Msg = "重新登陆"
	}
	WriteJSON(w, res)
}

// 查询测试状态
func Csvstatus(w http.ResponseWriter, r *http.Request) {
	defer Catch()
	res := JSON{}
	if CheckSession(w, r) {
		fn := r.FormValue("fn")
		if fn == "" {
			res.Msg = "fn不能为空"
		} else {
			res.Status = true
			res.Data = task.TEST.Get(fn)
		}
	} else {
		res.Msg = "重新登陆"
	}
	WriteJSON(w, res)
}

// csv下载
func CsvDown(w http.ResponseWriter, r *http.Request) {
	defer Catch()
	fn := r.FormValue("fn")
	tl := task.TEST.Get(fn)
	if tl != nil {
		if tl[0] == 1 {
			w.Header().Add("Content-type", "text/csv")
			w.Header().Add("Content-disposition", "attachment;filename="+fn)
			by, _ := ioutil.ReadFile("./csv/" + fn)
			w.Write(by)
		} else {
			w.Write([]byte(fmt.Sprintf("sorry,文件未处理完成...总数:%d,已完成:%d", tl[1], tl[2])))
		}
	} else {
		w.Write([]byte("sorry,filename not exists..."))
	}

}

// 更新运行
func UpdateRun(w http.ResponseWriter, r *http.Request) {
	defer Catch()
	res := JSON{}
	if CheckSession(w, r) {
		_id := r.FormValue("_id")
		if _id == "" {
			res.Msg = "_id不能为空"
		} else {
			s_mgourl := r.FormValue("s_mgourl")
			s_mgodb := r.FormValue("s_mgodb")
			s_coll := r.FormValue("s_coll")
			i_poolsize := r.FormValue("i_poolsize")
			s_esurl := r.FormValue("s_esurl")
			s_esdb := r.FormValue("s_esdb")
			s_escoll := r.FormValue("s_escoll")
			s_startid := r.FormValue("s_startid")
			s_endid := r.FormValue("s_endid")
			s_query := r.FormValue("s_query")
			log.Println("---Update to run", _id)
			compare := r.FormValue("bcompare")
			bcompare := false
			if compare == "y" {
				bcompare = true
			}
			bs := task.LoadUpdateTask(_id, s_mgourl, s_mgodb, s_coll, i_poolsize, s_esurl, s_esdb, s_escoll, s_startid, s_endid, s_query, bcompare)
			res.Status = bs
			res.Data = _id
		}
	} else {
		res.Msg = "重新登陆"
	}
	WriteJSON(w, res)

}
