package accounts

import (
	"fmt"
	"os"
	"sync"
	"syscall"
	"time"

	"github.com/godbus/dbus"
	"github.com/linuxdeepin/dde-daemon/accounts/patterns"
	"github.com/linuxdeepin/go-lib/procfs"
)

func (u *User) getSenderCommand(sender dbus.Sender) string {
	pid, err := u.service.GetConnPID(string(sender))
	if err != nil {
		logger.Warning(err)
		return ""
	}
	proc := procfs.Process(pid)
	exe, err := proc.Exe()
	if err != nil {
		logger.Warning(err)
		return ""
	}
	return exe
}

func (u *User) resetPattern(sender dbus.Sender) error {
	caller := &patterns.Caller{
		Name:     u.UserName,
		FullName: u.FullName,
		Uid:      u.Uid,
		Locale:   u.Locale,
		Sender:   string(sender),
	}
	return u.doResetPattern(caller, 3)
}

var resetPatternLock sync.Mutex
var resetPatternProcess *os.Process

func (u *User) doResetPattern(caller *patterns.Caller, count int) error {
	resetPatternLock.Lock()

	if resetPatternProcess != nil {
		err := syscall.Kill(-resetPatternProcess.Pid, syscall.SIGTERM)
		if err != nil {
			logger.Warning(err)
		}
		resetPatternLock.Unlock()

		// 等待协程结束
		if count > 0 {
			logger.Debug("retry after 100ms")
			time.Sleep(100 * time.Millisecond)
			return u.doResetPattern(caller, count-1)
		} else {
			return fmt.Errorf("kill pwd changer process failed")
		}
	}

	m, err := patterns.NewReset(u.service, caller)
	if err != nil {
		resetPatternLock.Unlock()
		return fmt.Errorf("setup reset manager fail: %v", err)
	}

	resetPatternProcess, err = m.RunDialog()
	resetPatternLock.Unlock()
	if err != nil {
		m.Clean()
		return err
	}

	go func() {
		defer func() {
			resetPatternLock.Lock()
			resetPatternProcess = nil
			resetPatternLock.Unlock()
		}()
		m.Wait()
		m.Clean()

		dm, err := patterns.GetDataManager(u.UserName)
		if err == nil {
			u.PropsMu.Lock()
			u.setPropPatternEnabled(dm.GetPatternEnabled())
			u.setPropPatternState(dm.GetPatternState())
			u.PropsMu.Unlock()
		}
	}()

	return nil
}

func (u *User) clearPattern() {
	if err := patterns.RemoveDataManager(u.UserName); err != nil {
		logger.Warning(err)
	}
}
