package main

import (
	"context"
	"os"
	"path/filepath"
	"runtime"
	"syscall"
	"time"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

var databaseManager = new(MongoDbManager)

type MongoDbManager struct {
	client               *mongo.Client
	Admins               *mongo.Collection
	Departments          *mongo.Collection
	Employees            *mongo.Collection
	WorkingDayStatistics *mongo.Collection
	StatisticsTables     *mongo.Collection
	WorkingDayInfos      *mongo.Collection
	HolidayInfos         *mongo.Collection
	ViewCodes            *mongo.Collection
	EmailSettings        *mongo.Collection
	DomainSettings       *mongo.Collection
	MessageTemplates     *mongo.Collection
	AttendanceDatas      *mongo.Collection
	DashBoards           *mongo.Collection
}

func (manager *MongoDbManager) AddAttendanceData(attendanceData *AttendanceData) {
	_, err := manager.AttendanceDatas.InsertOne(context.TODO(), *attendanceData)
	if err != nil {
		Logger.Error(err.Error())
		panic(any(err))
	}
}

func (manager *MongoDbManager) GetAttendanceDatas(employeeId string, start time.Time, end time.Time) []*AttendanceData {
	var result []*AttendanceData
	sort := bson.D{{Key: "day", Value: -1}}
	findOptions := options.Find()
	findOptions.SetSort(sort)
	filter := bson.M{"employeeid": employeeId, "day": bson.M{"$gte": start, "$lte": end}}
	cursor, err := manager.AttendanceDatas.Find(context.TODO(), filter, findOptions)
	if err == nil {
		defer func() {
			err := cursor.Close(context.TODO())
			if err != nil {
				return
			}
		}()
		for cursor.Next(context.TODO()) {
			var attendanceData AttendanceData
			err := cursor.Decode(&attendanceData)
			if err != nil {
				Logger.Error(err.Error())
				return nil
			}
			result = append(result, &attendanceData)
		}
		if err := cursor.Err(); err != nil {
			Logger.Error(err.Error())
			return nil
		} else {
			return result
		}
	}
	return nil
}

func (manager *MongoDbManager) GetEmployeeCount() int64 {
	count, err := manager.Employees.EstimatedDocumentCount(context.TODO())
	if err != nil {
		Logger.Error(err.Error())
		panic(any(err))
	}
	return count
}

func (manager *MongoDbManager) GetStruggleEmployeeCount() int64 {
	filter := bson.D{{Key: "isstruggle", Value: true}}
	count, err := manager.Employees.CountDocuments(context.TODO(), filter)
	if err != nil {
		Logger.Error(err.Error())
		panic(any(err))
	}
	return count
}

func (manager *MongoDbManager) AddHolidayInfo(holidayInfo *HolidayInfo) {
	_, err := manager.HolidayInfos.InsertOne(context.TODO(), *holidayInfo)
	if err != nil {
		Logger.Error(err.Error())
		panic(any(err))
	}
}

func (manager *MongoDbManager) DeleteHolidayInfo(holidayInfoId string) {
	filter := bson.D{{Key: "id", Value: holidayInfoId}}
	_, err := manager.HolidayInfos.DeleteOne(context.TODO(), filter)
	if err != nil {
		Logger.Error(err.Error())
		panic(any(err))
	}
}

func (manager *MongoDbManager) GetHolidayInfo(day time.Time) *HolidayInfo {
	filter := bson.D{{Key: "holiday", Value: day}}
	result := manager.HolidayInfos.FindOne(context.TODO(), filter)
	if result != nil {
		var holidayInfo = new(HolidayInfo)
		err := result.Decode(holidayInfo)
		if err == nil {
			return holidayInfo
		}
	}
	return nil
}

func (manager *MongoDbManager) UpdateHolidayInfo(holidayInfo *HolidayInfo) {
	filter := bson.D{{Key: "id", Value: holidayInfo.Id}}
	update := bson.D{{Key: "$set", Value: bson.D{{Key: "title", Value: holidayInfo.Title}, {Key: "holiday", Value: holidayInfo.Holiday}, {Key: "isadjusted", Value: holidayInfo.IsAdjusted}, {Key: "adjustedday", Value: holidayInfo.AdjustedDay}, {Key: "isnationallegal", Value: holidayInfo.IsNationalLegal}}}}
	_, err := manager.HolidayInfos.UpdateOne(context.TODO(), filter, update)
	if err != nil {
		Logger.Error(err.Error())
		panic(any(err))
	}
}

func (manager *MongoDbManager) GetHolidayDayInfos(start time.Time, end time.Time) []*HolidayInfo {
	var result []*HolidayInfo
	sort := bson.D{{Key: "holiday", Value: -1}}
	findOptions := options.Find()
	findOptions.SetSort(sort)
	filter := bson.M{"holiday": bson.M{"$gte": start, "$lte": end}}
	cursor, err := manager.HolidayInfos.Find(context.TODO(), filter, findOptions)
	if err == nil {
		defer func() {
			err := cursor.Close(context.TODO())
			if err != nil {
				return
			}
		}()
		for cursor.Next(context.TODO()) {
			var holidayInfo HolidayInfo
			err := cursor.Decode(&holidayInfo)
			if err != nil {
				Logger.Error(err.Error())
				return nil
			}
			result = append(result, &holidayInfo)
		}
		if err := cursor.Err(); err != nil {
			Logger.Error(err.Error())
			return nil
		} else {
			return result
		}
	}
	return nil
}

func (manager *MongoDbManager) AddEmployee(employee *Employee) {
	_, err := manager.Employees.InsertOne(context.TODO(), *employee)
	if err != nil {
		Logger.Error(err.Error())
		panic(any(err))
	}
}

func (manager *MongoDbManager) DeleteEmployee(employeeId string) {
	filter := bson.D{{Key: "id", Value: employeeId}}
	_, err := manager.Employees.DeleteOne(context.TODO(), filter)
	if err != nil {
		Logger.Error(err.Error())
		panic(any(err))
	}
}

func (manager *MongoDbManager) UpdateEmployee(employee *Employee) {
	filter := bson.D{{Key: "id", Value: employee.Id}}
	update := bson.D{{Key: "$set", Value: bson.D{{Key: "name", Value: employee.Name}, {Key: "title", Value: employee.Title}, {Key: "email", Value: employee.Email}, {Key: "attendancerules", Value: employee.AttendanceRules}, {Key: "departmentid", Value: employee.DepartmentId}}}}
	opts := options.Update().SetUpsert(false)
	_, err := manager.Employees.UpdateOne(context.TODO(), filter, update, opts)
	if err != nil {
		Logger.Error(err.Error())
		panic(any(err))
	}
}

func (manager *MongoDbManager) UpdateEmployeeDepartment(employee *Employee) {
	filter := bson.D{{Key: "id", Value: employee.Id}}
	update := bson.D{{Key: "$set", Value: bson.D{{Key: "departmentid", Value: employee.DepartmentId}}}}
	opts := options.Update().SetUpsert(false)
	_, err := manager.Employees.UpdateOne(context.TODO(), filter, update, opts)
	if err != nil {
		Logger.Error(err.Error())
		panic(any(err))
	}
}

func (manager *MongoDbManager) UpdateEmployeeIsStruggle(employee *Employee) {
	filter := bson.D{{Key: "id", Value: employee.Id}}
	update := bson.D{{Key: "$set", Value: bson.D{{Key: "isstruggle", Value: employee.IsStruggle}}}}
	opts := options.Update().SetUpsert(false)
	_, err := manager.Employees.UpdateOne(context.TODO(), filter, update, opts)
	if err != nil {
		Logger.Error(err.Error())
		panic(any(err))
	}
}

func (manager *MongoDbManager) UpdateEmployeeIsReviewer(employee *Employee) {
	filter := bson.D{{Key: "id", Value: employee.Id}}
	update := bson.D{{Key: "$set", Value: bson.D{{Key: "isreviewer", Value: employee.IsReviewer}}}}
	opts := options.Update().SetUpsert(false)
	_, err := manager.Employees.UpdateOne(context.TODO(), filter, update, opts)
	if err != nil {
		Logger.Error(err.Error())
		panic(any(err))
	}
}

func (manager *MongoDbManager) GetEmployeeById(employeeId string) *Employee {
	filter := bson.D{{Key: "id", Value: employeeId}}
	result := manager.Employees.FindOne(context.TODO(), filter)
	if result != nil {
		var employee = new(Employee)
		err := result.Decode(employee)
		if err == nil {
			return employee
		}
	}
	return nil
}

func (manager *MongoDbManager) GetEmployeeByEmail(email string) *Employee {
	filter := bson.D{{Key: "email", Value: email}}
	result := manager.Employees.FindOne(context.TODO(), filter)
	if result != nil {
		var employee = new(Employee)
		err := result.Decode(employee)
		if err == nil {
			return employee
		}
	}
	return nil
}

func (manager *MongoDbManager) GetEmployeeByName(employeeName string) *Employee {
	filter := bson.D{{Key: "name", Value: employeeName}}
	result := manager.Employees.FindOne(context.TODO(), filter)
	if result != nil {
		var employee = new(Employee)
		err := result.Decode(employee)
		if err == nil {
			return employee
		}
	}
	return nil
}

func (manager *MongoDbManager) GetEmployeeMany(startIndex int, count int) []*Employee {
	var result []*Employee
	sort := bson.D{{Key: "name", Value: 1}}
	filter := bson.D{{}}
	findOptions := options.Find()
	findOptions.SetSort(sort)
	findOptions.SetLimit(int64(count))
	findOptions.SetSkip(int64(startIndex))
	cursor, err := manager.Employees.Find(context.TODO(), filter, findOptions)
	if err == nil {
		defer func() {
			err := cursor.Close(context.TODO())
			if err != nil {
				return
			}
		}()
		for cursor.Next(context.TODO()) {
			var employee Employee
			err := cursor.Decode(&employee)
			if err != nil {
				Logger.Error(err.Error())
				return nil
			}
			result = append(result, &employee)
		}
		if err := cursor.Err(); err != nil {
			Logger.Error(err.Error())
			return nil
		} else {
			return result
		}
	}
	return nil
}

func (manager *MongoDbManager) GetEmployeeManyByName(name string, startIndex int, count int) []*Employee {
	var result []*Employee
	sort := bson.D{{Key: "name", Value: 1}}
	filter := bson.D{{Key: "name", Value: name}}
	findOptions := options.Find()
	findOptions.SetSort(sort)
	findOptions.SetLimit(int64(count))
	findOptions.SetSkip(int64(startIndex))
	cursor, err := manager.Employees.Find(context.TODO(), filter, findOptions)
	if err == nil {
		defer func() {
			err := cursor.Close(context.TODO())
			if err != nil {
				return
			}
		}()
		for cursor.Next(context.TODO()) {
			var employee Employee
			err := cursor.Decode(&employee)
			if err != nil {
				Logger.Error(err.Error())
				return nil
			}
			result = append(result, &employee)
		}
		if err := cursor.Err(); err != nil {
			Logger.Error(err.Error())
			return nil
		} else {
			return result
		}
	}
	return nil
}

func (manager *MongoDbManager) GetReviewers() []*Employee {
	var result []*Employee
	sort := bson.D{{Key: "name", Value: 1}}
	filter := bson.D{{Key: "isreviewer", Value: true}}
	findOptions := options.Find()
	findOptions.SetSort(sort)
	cursor, err := manager.Employees.Find(context.TODO(), filter, findOptions)
	if err == nil {
		defer func() {
			err := cursor.Close(context.TODO())
			if err != nil {
				return
			}
		}()
		for cursor.Next(context.TODO()) {
			var employee Employee
			err := cursor.Decode(&employee)
			if err != nil {
				Logger.Error(err.Error())
				return nil
			}
			result = append(result, &employee)
		}
		if err := cursor.Err(); err != nil {
			Logger.Error(err.Error())
			return nil
		} else {
			return result
		}
	}
	return nil
}

func (manager *MongoDbManager) GetEmployeeManyByDepartmentId(departmentId int) []*Employee {
	var result []*Employee
	sort := bson.D{{Key: "name", Value: 1}}
	filter := bson.D{{Key: "departmentid", Value: departmentId}}
	findOptions := options.Find()
	findOptions.SetSort(sort)
	cursor, err := manager.Employees.Find(context.TODO(), filter, findOptions)
	if err == nil {
		defer func() {
			err := cursor.Close(context.TODO())
			if err != nil {
				return
			}
		}()
		for cursor.Next(context.TODO()) {
			var employee Employee
			err := cursor.Decode(&employee)
			if err != nil {
				Logger.Error(err.Error())
				return nil
			}
			result = append(result, &employee)
		}
		if err := cursor.Err(); err != nil {
			Logger.Error(err.Error())
			return nil
		} else {
			return result
		}
	}
	return nil
}

func (manager *MongoDbManager) GetStruggleEmployeeMany() []*Employee {
	var result []*Employee
	sort := bson.D{{Key: "name", Value: 1}}
	filter := bson.D{{Key: "isstruggle", Value: true}}
	findOptions := options.Find()
	findOptions.SetSort(sort)
	cursor, err := manager.Employees.Find(context.TODO(), filter, findOptions)
	if err == nil {
		defer func() {
			err := cursor.Close(context.TODO())
			if err != nil {
				return
			}
		}()
		for cursor.Next(context.TODO()) {
			var employee Employee
			err := cursor.Decode(&employee)
			if err != nil {
				Logger.Error(err.Error())
				return nil
			}
			result = append(result, &employee)
		}
		if err := cursor.Err(); err != nil {
			Logger.Error(err.Error())
			return nil
		} else {
			return result
		}
	}
	return nil
}

func (manager *MongoDbManager) AddWorkingDayInfo(workingDayInfo *WorkingDayInfo) {
	_, err := manager.WorkingDayInfos.InsertOne(context.TODO(), *workingDayInfo)
	if err != nil {
		Logger.Error(err.Error())
		panic(any(err))
	}
}

func (manager *MongoDbManager) DeleteWorkingDayInfo(workingDayInfoId string) {
	filter := bson.D{{Key: "id", Value: workingDayInfoId}}
	_, err := manager.WorkingDayInfos.DeleteOne(context.TODO(), filter)
	if err != nil {
		Logger.Error(err.Error())
		panic(any(err))
	}
}

func (manager *MongoDbManager) UpdateWorkingDayInfo(workingDayInfo *WorkingDayInfo) {
	filter := bson.D{{Key: "id", Value: workingDayInfo.Id}}
	update := bson.D{{Key: "$set", Value: bson.D{{Key: "adjusted", Value: workingDayInfo.Adjusted}, {Key: "adjustedObtainedunits", Value: workingDayInfo.AdjustedObtainedUnits}, {Key: "adjustdescription", Value: workingDayInfo.AdjustDescription}}}}
	_, err := manager.WorkingDayInfos.UpdateOne(context.TODO(), filter, update)
	if err != nil {
		Logger.Error(err.Error())
		panic(any(err))
	}
}

func (manager *MongoDbManager) GetWorkingDayInfoById(workingDayInfoId string) *WorkingDayInfo {
	filter := bson.D{{Key: "id", Value: workingDayInfoId}}
	result := manager.WorkingDayInfos.FindOne(context.TODO(), filter)
	if result != nil {
		var workingDayInfo = new(WorkingDayInfo)
		err := result.Decode(workingDayInfo)
		if err == nil {
			return workingDayInfo
		}
	}
	return nil
}

func (manager *MongoDbManager) GetWorkingDayInfoMany(employeeId string, statisticsId string) []*WorkingDayInfo {
	var result []*WorkingDayInfo
	sort := bson.D{{Key: "day", Value: 1}}
	filter := bson.M{"employeeid": employeeId, "statisticsid": statisticsId}
	findOptions := options.Find()
	findOptions.SetSort(sort)
	cursor, err := manager.WorkingDayInfos.Find(context.TODO(), filter, findOptions)
	if err == nil {
		defer func() {
			err := cursor.Close(context.TODO())
			if err != nil {
				return
			}
		}()
		for cursor.Next(context.TODO()) {
			var workingDayInfo WorkingDayInfo
			err := cursor.Decode(&workingDayInfo)
			if err != nil {
				Logger.Error(err.Error())
				return nil
			}
			result = append(result, &workingDayInfo)
		}
		if err := cursor.Err(); err != nil {
			Logger.Error(err.Error())
			return nil
		} else {
			return result
		}
	}
	return nil
}

func (manager *MongoDbManager) AddWorkingDayStatistics(workingDayStatistics *WorkingDayStatistics) {
	_, err := manager.WorkingDayStatistics.InsertOne(context.TODO(), *workingDayStatistics)
	if err != nil {
		Logger.Error(err.Error())
		panic(any(err))
	}
}

func (manager *MongoDbManager) GetWorkingDayStatisticsById(workingDayStatisticsId string) *WorkingDayStatistics {
	filter := bson.D{{Key: "id", Value: workingDayStatisticsId}}
	result := manager.WorkingDayStatistics.FindOne(context.TODO(), filter)
	if result != nil {
		var workingDayStatistics = new(WorkingDayStatistics)
		err := result.Decode(workingDayStatistics)
		if err == nil {
			return workingDayStatistics
		}
	}
	return nil
}

func (manager *MongoDbManager) GetWorkingDayStatisticsByIds(workingDayStatisticsIds []string) []*WorkingDayStatistics {
	var result []*WorkingDayStatistics
	for i := 0; i < len(workingDayStatisticsIds); i++ {
		result = append(result, manager.GetWorkingDayStatisticsById(workingDayStatisticsIds[i]))
	}
	return result
}

func (manager *MongoDbManager) GetWorkingDayStatisticsByStartEnd(employeeId string, start, end time.Time) *WorkingDayStatistics {
	filter := bson.M{"employee.id": employeeId, "day": bson.M{"$gte": start, "$lte": end}}
	result := manager.WorkingDayInfos.FindOne(context.TODO(), filter)
	if result != nil {
		var workingDayStatistics = new(WorkingDayStatistics)
		err := result.Decode(workingDayStatistics)
		if err == nil {
			return workingDayStatistics
		}
	}
	return nil
}

func (manager *MongoDbManager) UpdateWorkingDayStatistics(workingDayStatistics *WorkingDayStatistics) {
	filter := bson.D{{Key: "id", Value: workingDayStatistics.Id}}
	update := bson.M{
		"$set": bson.M{
			"adjusted":             workingDayStatistics.Adjusted,
			"adjustedby":           workingDayStatistics.AdjustedBy,
			"adjustdescription":    workingDayStatistics.AdjustDescription,
			"comment":              workingDayStatistics.Comment,
			"adjustedreachedcount": workingDayStatistics.AdjustedReachedCount,
			"reviewer":             workingDayStatistics.Reviewer,
		},
	}
	_, err := manager.WorkingDayStatistics.UpdateOne(context.TODO(), filter, update)
	if err != nil {
		Logger.Error(err.Error())
		panic(any(err))
	}
}

func (manager *MongoDbManager) UpdateWorkingDayStatisticsComment(workingDayStatisticsId string, comment string) {
	filter := bson.D{{Key: "id", Value: workingDayStatisticsId}}
	update := bson.M{
		"$set": bson.M{
			"comment": comment,
		},
	}
	_, err := manager.WorkingDayStatistics.UpdateOne(context.TODO(), filter, update)
	if err != nil {
		Logger.Error(err.Error())
		panic(any(err))
	}
}

func (manager *MongoDbManager) AddStatisticsTable(statisticsTable *StatisticsTable) {
	_, err := manager.StatisticsTables.InsertOne(context.TODO(), *statisticsTable)
	if err != nil {
		Logger.Error(err.Error())
		panic(any(err))
	}
}

func (manager *MongoDbManager) GetStatisticsTableByTitle(title string) *StatisticsTable {
	filter := bson.D{{Key: "title", Value: title}}
	result := manager.StatisticsTables.FindOne(context.TODO(), filter)
	if result != nil {
		var statisticsTable = new(StatisticsTable)
		err := result.Decode(statisticsTable)
		if err == nil {
			return statisticsTable
		}
	}
	return nil
}

func (manager *MongoDbManager) GetStatisticsTableById(id string) *StatisticsTable {
	filter := bson.D{{Key: "id", Value: id}}
	result := manager.StatisticsTables.FindOne(context.TODO(), filter)
	if result != nil {
		var statisticsTable = new(StatisticsTable)
		err := result.Decode(statisticsTable)
		if err == nil {
			return statisticsTable
		}
	}
	return nil
}

func (manager *MongoDbManager) DeleteStatisticsTable(statisticsTableId string) {
	filter := bson.D{{Key: "id", Value: statisticsTableId}}
	_, err := manager.StatisticsTables.DeleteOne(context.TODO(), filter)
	if err != nil {
		Logger.Error(err.Error())
		panic(any(err))
	}
}

func (manager *MongoDbManager) GetStatisticsTableMany() []*StatisticsTable {
	var result []*StatisticsTable
	filter := bson.D{}
	sort := bson.D{{Key: "createtime", Value: -1}}
	findOptions := options.Find()
	findOptions.SetSort(sort)
	findOptions.SetLimit(int64(12))
	findOptions.SetSkip(int64(0))
	cursor, err := manager.StatisticsTables.Find(context.TODO(), filter, findOptions)
	if err == nil {
		defer func() {
			err := cursor.Close(context.TODO())
			if err != nil {
				return
			}
		}()
		for cursor.Next(context.TODO()) {
			var statisticsTable StatisticsTable
			err := cursor.Decode(&statisticsTable)
			if err != nil {
				Logger.Error(err.Error())
				return nil
			}
			result = append(result, &statisticsTable)
		}
		if err := cursor.Err(); err != nil {
			Logger.Error(err.Error())
			return nil
		} else {
			return result
		}
	}
	return nil
}

func (manager *MongoDbManager) AddDepartment(dep *Department) {
	_, err := manager.Departments.InsertOne(context.TODO(), *dep)
	if err != nil {
		Logger.Error(err.Error())
		panic(any(err))
	}
}

func (manager *MongoDbManager) DeleteDepartment(depId string) {
	filter := bson.D{{Key: "id", Value: depId}}
	_, err := manager.Departments.DeleteOne(context.TODO(), filter)
	if err != nil {
		Logger.Error(err.Error())
		panic(any(err))
	}
}

func (manager *MongoDbManager) UpdateDepartment(dep *Department) {
	filter := bson.D{{Key: "id", Value: dep.Id}}
	update := bson.D{{Key: "$set", Value: bson.D{{Key: "name", Value: dep.Name}, {Key: "parentid", Value: dep.ParentId}}}}
	opts := options.Update().SetUpsert(false)
	_, err := manager.Departments.UpdateOne(context.TODO(), filter, update, opts)
	if err != nil {
		Logger.Error(err.Error())
		panic(any(err))
	}
}

func (manager *MongoDbManager) UpdateDepartmentParent(dep *Department) {
	filter := bson.D{{Key: "id", Value: dep.Id}}
	update := bson.D{{Key: "$set", Value: bson.D{{Key: "parentid", Value: dep.ParentId}}}}
	opts := options.Update().SetUpsert(false)
	_, err := manager.Departments.UpdateOne(context.TODO(), filter, update, opts)
	if err != nil {
		Logger.Error(err.Error())
		panic(any(err))
	}
}

func (manager *MongoDbManager) GetDepartmentById(depId int) *Department {
	filter := bson.D{{Key: "id", Value: depId}}
	result := manager.Departments.FindOne(context.TODO(), filter)
	if result != nil {
		var dep = new(Department)
		err := result.Decode(dep)
		if err == nil {
			return dep
		}
	}
	return nil
}

func (manager *MongoDbManager) GetDepartmentsByParentId(parentId int) []*Department {
	var result []*Department
	sort := bson.D{{Key: "name", Value: -1}}
	filter := bson.D{{Key: "parentid", Value: parentId}}
	findOptions := options.Find()
	findOptions.SetSort(sort)
	cursor, err := manager.Departments.Find(context.TODO(), filter, findOptions)
	if err == nil {
		defer func() { cursor.Close(context.TODO()) }()
		for cursor.Next(context.TODO()) {
			var department Department
			err := cursor.Decode(&department)
			if err != nil {
				Logger.Error(err.Error())
				return nil
			}
			result = append(result, &department)
		}
		if err := cursor.Err(); err != nil {
			Logger.Error(err.Error())
			return nil
		} else {
			return result
		}
	}
	return nil
}

func (manager *MongoDbManager) GetDepartmentByName(depName string) *Department {
	filter := bson.D{{Key: "name", Value: depName}}
	result := manager.Departments.FindOne(context.TODO(), filter)
	if result != nil {
		var dep = new(Department)
		err := result.Decode(dep)
		if err == nil {
			return dep
		}
	}
	return nil
}

func (manager *MongoDbManager) UpdateAdminPassword(admin *Admin) {
	filter := bson.D{{Key: "id", Value: admin.Id}}
	update := bson.D{{Key: "$set", Value: bson.D{{Key: "password", Value: admin.Password}}}}
	opts := options.Update().SetUpsert(false)
	_, err := manager.Admins.UpdateOne(context.TODO(), filter, update, opts)
	if err != nil {
		Logger.Error(err.Error())
		panic(any(err))
	}
}

func (manager *MongoDbManager) AddAdmin(admin *Admin) {
	_, err := manager.Admins.InsertOne(context.TODO(), *admin)
	if err != nil {
		Logger.Error(err.Error())
		panic(any(err))
	}
}

func (manager *MongoDbManager) GetAdminByName(name string) *Admin {
	filter := bson.M{"name": primitive.Regex{Pattern: name, Options: "i"}}
	result := manager.Admins.FindOne(context.TODO(), filter)
	if result != nil {
		var admin = new(Admin)
		err := result.Decode(admin)
		if err == nil {
			return admin
		}
	}
	return nil
}

func (manager *MongoDbManager) GetAdminById(id string) *Admin {
	filter := bson.D{{Key: "id", Value: id}}
	result := manager.Admins.FindOne(context.TODO(), filter)
	if result != nil {
		var admin = new(Admin)
		err := result.Decode(admin)
		if err == nil {
			return admin
		}
	}
	return nil
}

func (manager *MongoDbManager) AddViewCode(viewCode *ViewCode) {
	_, err := manager.ViewCodes.InsertOne(context.TODO(), *viewCode)
	if err != nil {
		Logger.Error(err.Error())
		panic(any(err))
	}
}

func (manager *MongoDbManager) GetViewCode(code string) *ViewCode {
	filter := bson.D{{Key: "code", Value: code}}
	result := manager.ViewCodes.FindOne(context.TODO(), filter)
	if result != nil {
		var viewCode = new(ViewCode)
		err := result.Decode(viewCode)
		if err == nil {
			return viewCode
		}
	}
	return nil
}

func (manager *MongoDbManager) AddEmailSetting(emailSetting *EmailSetting) {
	_, err := manager.EmailSettings.InsertOne(context.TODO(), *emailSetting)
	if err != nil {
		Logger.Error(err.Error())
		panic(any(err))
	}
}

func (manager *MongoDbManager) UpdateEmailSetting(emailSetting *EmailSetting) {
	filter := bson.D{{}}
	update := bson.D{{Key: "$set", Value: bson.D{{Key: "host", Value: emailSetting.Host}, {Key: "port", Value: emailSetting.Port}, {Key: "sender", Value: emailSetting.Sender}, {Key: "senderpassword", Value: emailSetting.SenderPassword}}}}
	opts := options.Update().SetUpsert(false)
	_, err := manager.EmailSettings.UpdateOne(context.TODO(), filter, update, opts)
	if err != nil {
		Logger.Error(err.Error())
		panic(any(err))
	}
}

func (manager *MongoDbManager) GetEmailSetting() *EmailSetting {
	filter := bson.D{{}}
	result := manager.EmailSettings.FindOne(context.TODO(), filter)
	if result != nil {
		var emailSetting = new(EmailSetting)
		err := result.Decode(emailSetting)
		if err == nil {
			return emailSetting
		}
	}
	return nil
}

func (manager *MongoDbManager) AddDomainSetting(domainSetting *DomainSetting) {
	_, err := manager.DomainSettings.InsertOne(context.TODO(), *domainSetting)
	if err != nil {
		Logger.Error(err.Error())
		panic(any(err))
	}
}

func (manager *MongoDbManager) UpdateDomainSetting(domainSetting *DomainSetting) {
	filter := bson.D{{}}
	update := bson.D{{Key: "$set", Value: bson.D{{Key: "domain", Value: domainSetting.Domain}}}}
	opts := options.Update().SetUpsert(false)
	_, err := manager.DomainSettings.UpdateOne(context.TODO(), filter, update, opts)
	if err != nil {
		Logger.Error(err.Error())
		panic(any(err))
	}
}

func (manager *MongoDbManager) AddMessageTemplate(template *MessageTemplate) {
	_, err := manager.MessageTemplates.InsertOne(context.TODO(), *template)
	if err != nil {
		Logger.Error(err.Error())
		panic(any(err))
	}
}

func (manager *MongoDbManager) DeleteMessageTemplate(template *MessageTemplate) {
	filter := bson.D{{Key: "id", Value: template.Id}}
	_, err := manager.MessageTemplates.DeleteOne(context.TODO(), filter)
	if err != nil {
		Logger.Error(err.Error())
		panic(any(err))
	}
}

func (manager *MongoDbManager) GetMessageTemplate(name string) *MessageTemplate {
	filter := bson.D{{Key: "name", Value: name}}
	result := manager.MessageTemplates.FindOne(context.TODO(), filter)
	if result != nil {
		var template = new(MessageTemplate)
		err := result.Decode(template)
		if err == nil {
			return template
		}
	}
	return nil
}

func (manager *MongoDbManager) UpdateMessageTemplate(template *MessageTemplate) {
	filter := bson.D{{Key: "name", Value: template.Name}}
	update := bson.D{{Key: "$set", Value: bson.D{{Key: "content", Value: template.Content}}}}
	opts := options.Update().SetUpsert(false)
	_, err := manager.MessageTemplates.UpdateOne(context.TODO(), filter, update, opts)
	if err != nil {
		Logger.Error(err.Error())
		panic(any(err))
	}
}

func (manager *MongoDbManager) GetDomainSetting() *DomainSetting {
	filter := bson.D{{}}
	result := manager.DomainSettings.FindOne(context.TODO(), filter)
	if result != nil {
		var domainSetting = new(DomainSetting)
		err := result.Decode(domainSetting)
		if err == nil {
			return domainSetting
		}
	}
	return nil
}

func (manager *MongoDbManager) CreateClient() *mongo.Client {
	clientOptions := options.Client().ApplyURI("mongodb://localhost:27017").SetServerSelectionTimeout(3 * time.Second)
	client, err := mongo.Connect(context.TODO(), clientOptions)
	if err != nil {
		Logger.Error(err.Error())
		return nil
	}
	err = client.Ping(context.TODO(), nil)
	if err != nil {
		Logger.Error(err.Error())
		return nil
	}
	return client
}

func (manager *MongoDbManager) StartMongo() {
	path, err := os.Executable()
	if err != nil {
		Logger.Error("Can not get the right path: " + err.Error())
	}
	dir := filepath.Dir(path)
	dbDir := filepath.Join(dir, "database")
	if _, err := os.Stat(dbDir); os.IsNotExist(err) {
		if err = os.MkdirAll(dbDir, os.ModePerm); err == nil {
			if runtime.GOOS != "windows" {
				if err = os.Chmod(dbDir, os.ModePerm); err != nil {
					Logger.Error("Set dir mode failed: " + err.Error())
					return
				}
			}
		} else {
			Logger.Error("Create dir mode failed: " + err.Error())
			return
		}
	}
	mongoDb := filepath.Join(dir, "mongod.exe")
	procAttr := new(os.ProcAttr)
	procAttr.Dir = dir
	procAttr.Files = []*os.File{os.Stdin, os.Stdout, os.Stderr}
	procAttr.Sys = &syscall.SysProcAttr{}
	startArgs := []string{mongoDb, "--dbpath", filepath.Join(dir, "database"), "--port", "27017", "--maxConns", "1024"}
	if runtime.GOOS == "windows" {
		_, err := os.StartProcess(mongoDb, startArgs, procAttr)
		if err != nil {
			Logger.Error("Start mongod failed: " + err.Error())
			return
		}
	} else {
		mongoDb = filepath.Join(dir, "mongod")
		startArgs[0] = mongoDb
		if err = os.Chmod(mongoDb, os.ModePerm); err != nil {
			Logger.Error("Set file mode failed: " + err.Error())
			return
		}
		_, err := os.StartProcess(mongoDb, startArgs, procAttr)
		if err != nil {
			Logger.Error("Start mongod failed: " + err.Error())
			return
		}
	}
}

func (manager *MongoDbManager) AddOrUpdateDashBoardItem(itemName string, value int) {
	item := manager.GetDashBoardItem(itemName)
	if item == nil {
		item = new(DashBoardItem)
		item.Id = NewUUId()
		item.ItemName = itemName
		item.Data = value
		_, err := manager.DashBoards.InsertOne(context.TODO(), item)
		if err != nil {
			Logger.Error(err.Error())
			panic(any(err))
		}
	} else {
		filter := bson.D{{Key: "itemname", Value: itemName}}
		update := bson.D{{Key: "$set", Value: bson.D{{Key: "data", Value: value}}}}
		opts := options.Update().SetUpsert(false)
		_, err := manager.DashBoards.UpdateOne(context.TODO(), filter, update, opts)
		if err != nil {
			Logger.Error(err.Error())
			panic(any(err))
		}
	}

}

func (manager *MongoDbManager) GetDashBoardItem(itemName string) *DashBoardItem {
	filter := bson.D{{Key: "itemname", Value: itemName}}
	result := manager.DashBoards.FindOne(context.TODO(), filter)
	if result != nil {
		var item = new(DashBoardItem)
		err := result.Decode(item)
		if err == nil {
			return item
		}
	}
	return nil
}

func (manager *MongoDbManager) Initialize() {
	client := manager.CreateClient()
	for client == nil {
		manager.StartMongo()
		time.Sleep(1 * time.Second)
		client = manager.CreateClient()
	}
	manager.client = client
	manager.Admins = client.Database("sss").Collection("Admin")
	manager.Admins.Indexes().CreateOne(context.TODO(), mongo.IndexModel{Keys: bson.M{"id": 1}, Options: nil})
	manager.Admins.Indexes().CreateOne(context.TODO(), mongo.IndexModel{Keys: bson.M{"name": 1}, Options: nil})

	manager.Employees = client.Database("sss").Collection("Employee")
	manager.Employees.Indexes().CreateOne(context.TODO(), mongo.IndexModel{Keys: bson.M{"id": 1}, Options: nil})
	manager.Employees.Indexes().CreateOne(context.TODO(), mongo.IndexModel{Keys: bson.M{"departmentid": 1}, Options: nil})
	manager.Employees.Indexes().CreateOne(context.TODO(), mongo.IndexModel{Keys: bson.M{"isreviewer": 1}, Options: nil})
	manager.Employees.Indexes().CreateOne(context.TODO(), mongo.IndexModel{Keys: bson.M{"isstruggle": 1}, Options: nil})

	manager.WorkingDayInfos = client.Database("sss").Collection("WorkingDayInfo")
	manager.WorkingDayInfos.Indexes().CreateOne(context.TODO(), mongo.IndexModel{Keys: bson.M{"id": 1}, Options: nil})
	manager.WorkingDayInfos.Indexes().CreateOne(context.TODO(), mongo.IndexModel{Keys: bson.M{"statisticsid": 1}, Options: nil})
	manager.WorkingDayInfos.Indexes().CreateOne(context.TODO(), mongo.IndexModel{Keys: bson.M{"day": 1}, Options: nil})
	manager.WorkingDayInfos.Indexes().CreateOne(context.TODO(), mongo.IndexModel{Keys: bson.D{{Key: "employeeid", Value: 1}, {Key: "statisticsid", Value: 1}}, Options: nil})

	manager.WorkingDayStatistics = client.Database("sss").Collection("WorkingDayStatistics")
	manager.WorkingDayStatistics.Indexes().CreateOne(context.TODO(), mongo.IndexModel{Keys: bson.M{"id": 1}, Options: nil})

	manager.StatisticsTables = client.Database("sss").Collection("WorkingDayStatisticsCollection")
	manager.StatisticsTables.Indexes().CreateOne(context.TODO(), mongo.IndexModel{Keys: bson.M{"id": 1}, Options: nil})
	manager.StatisticsTables.Indexes().CreateOne(context.TODO(), mongo.IndexModel{Keys: bson.M{"title": 1}, Options: nil})

	manager.Departments = client.Database("sss").Collection("Department")
	manager.Departments.Indexes().CreateOne(context.TODO(), mongo.IndexModel{Keys: bson.M{"id": 1}, Options: nil})
	manager.Departments.Indexes().CreateOne(context.TODO(), mongo.IndexModel{Keys: bson.M{"parentid": 1}, Options: nil})

	manager.HolidayInfos = client.Database("sss").Collection("HolidayInfo")
	manager.HolidayInfos.Indexes().CreateOne(context.TODO(), mongo.IndexModel{Keys: bson.M{"id": 1}, Options: nil})
	manager.HolidayInfos.Indexes().CreateOne(context.TODO(), mongo.IndexModel{Keys: bson.M{"holiday": 1}, Options: nil})

	manager.ViewCodes = client.Database("sss").Collection("ViewCode")
	manager.ViewCodes.Indexes().CreateOne(context.TODO(), mongo.IndexModel{Keys: bson.M{"id": 1}, Options: nil})
	manager.ViewCodes.Indexes().CreateOne(context.TODO(), mongo.IndexModel{Keys: bson.M{"code": 1}, Options: nil})

	manager.EmailSettings = client.Database("sss").Collection("EmailSetting")
	manager.DomainSettings = client.Database("sss").Collection("DomainSetting")
	manager.MessageTemplates = client.Database("sss").Collection("MessageTemplate")

	manager.DashBoards = client.Database("sss").Collection("DashBoard")

	manager.AttendanceDatas = client.Database("sss").Collection("AttendanceData")
	manager.AttendanceDatas.Indexes().CreateOne(context.TODO(), mongo.IndexModel{Keys: bson.M{"employeeid": 1}, Options: nil})
	manager.AttendanceDatas.Indexes().CreateOne(context.TODO(), mongo.IndexModel{Keys: bson.M{"day": 1}, Options: nil})
	manager.AttendanceDatas.Indexes().CreateOne(context.TODO(), mongo.IndexModel{Keys: bson.D{{Key: "employeeid", Value: 1}, {Key: "day", Value: 1}}, Options: nil})

	//Check admin account
	sysAdmin := manager.GetAdminByName("admin")
	if sysAdmin == nil {
		sysAdmin = new(Admin)
		sysAdmin.Id = NewUUId()
		sysAdmin.Name = "admin"
		sysAdmin.Password = "admin"
		manager.AddAdmin(sysAdmin)
	}

	rootAdmin := manager.GetAdminByName("root")
	if rootAdmin == nil {
		rootAdmin = new(Admin)
		rootAdmin.Id = NewUUId()
		rootAdmin.Name = "root"
		rootAdmin.Password = "root@123"
		manager.AddAdmin(rootAdmin)
	}
}

func (manager *MongoDbManager) Close() {
	err := manager.client.Disconnect(context.TODO())
	if err != nil {
		Logger.Error(err.Error())
	}
	Logger.Info("Connection to MongoDB closed.")
}
