package tools

import (
	"sync"
)

type SortMap struct {
	Index map[string]int
	Keys  []string
	Map   map[string]interface{}
	Lock  sync.Mutex
}
type KV [2]interface{}

func QuickSM(v map[string]interface{}, sorts []string) *SortMap {
	res := &SortMap{
		Index: map[string]int{},
		Keys:  []string{},
		Map:   map[string]interface{}{},
	}
	if sorts != nil {
		for _, kv := range sorts {
			res.AddKey(kv, v[kv])
		}
	} else {
		for k, kv := range v {
			res.AddKey(k, kv)
		}
	}
	return res
}

func QuickNewSortMap(v ...KV) *SortMap {
	res := &SortMap{
		Index: map[string]int{},
		Keys:  []string{},
		Map:   map[string]interface{}{},
	}
	for _, kv := range v {
		res.AddKey(kv[0].(string), kv[1])
	}
	return res
}

func NewSortMap() *SortMap {
	return &SortMap{
		Index: map[string]int{},
		Keys:  []string{},
		Map:   map[string]interface{}{},
	}
}

func (s *SortMap) AddKey(key string, val interface{}) {
	s.Lock.Lock()
	defer s.Lock.Unlock()
	//重复
	if s.Map[key] == nil {
		s.Index[key] = len(s.Keys)
		s.Keys = append(s.Keys, key)
	}
	s.Map[key] = val

}

func (s *SortMap) RemoveKey(key string) {
	s.Lock.Lock()
	defer s.Lock.Unlock()
	delete(s.Map, key)
	pos := s.Index[key]
	delete(s.Index, key)
	if len(s.Keys) > 0 {
		s.Keys = func() []string {
			newkeys := []string{}
			if len(s.Keys) > 1 {
				if pos == 0 {
					newkeys = append(newkeys, s.Keys[1:]...)
					//每一个都减一
					for k, v := range s.Index {
						s.Index[k] = v - 1
					}
				} else if pos == len(s.Keys) {
					newkeys = append(newkeys, s.Keys[:pos]...)
				} else {
					tmp := s.Keys[pos+1:]
					newkeys = append(append(newkeys, s.Keys[:pos]...), tmp...)
					for _, v := range tmp {
						s.Index[v] -= 1
					}
				}
			}
			return newkeys
		}()
	}
}
