package controllers

import (
	"context"
	"sparrow/pkg/models"
	"sparrow/pkg/rpcs"
	"sparrow/pkg/server"
	"sparrow/services/knowoapi/services"
	"strings"

	"github.com/opentracing/opentracing-go/ext"

	"github.com/opentracing/opentracing-go"

	"github.com/kataras/iris/v12"
)

// AppController api
type AppController struct {
	Ctx     iris.Context
	Service services.ApplicationService
	Token   Token
}

// Post 创建app
// POST /application
func (a *AppController) Post() {
	app := new(models.Application)
	if err := parseBody(a.Ctx, app); err != nil {
		badRequest(a.Ctx, err)
		return
	}
	app.VendorID = a.Token.getVendorID(a.Ctx)
	if app.AppIcon != "" {
		//move image
		args := &rpcs.ArgsMoveFile{
			Source: app.AppIcon,
			Target: "application",
		}
		reply := &rpcs.ReplyMoveFile{}
		span, ctx := opentracing.StartSpanFromContext(context.Background(), a.Ctx.Path())
		defer span.Finish()
		ext.SpanKindRPCClient.Set(span)
		ext.HTTPMethod.Set(span, a.Ctx.Method())
		err := server.RPCCallByName(ctx, "fileaccess", "FileAccess.MoveFile", args, reply)
		if err != nil {
			server.Log.Error(err)
			app.AppIcon = ""
		} else {
			app.AppIcon = reply.FilePath
		}
	}
	err := a.Service.Create(app)
	if err != nil {
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}
	done(a.Ctx, app)
}

// Get 获取我的app
// GET /application?pi=1&ps=&name=
func (a *AppController) Get() {
	pi, err := a.Ctx.URLParamInt("pi")
	if err != nil {
		badRequest(a.Ctx, err)
		return
	}
	ps, err := a.Ctx.URLParamInt("ps")
	if err != nil {
		badRequest(a.Ctx, err)
		return
	}
	name := a.Ctx.URLParam("name")
	ds, total, err := a.Service.GetVendorApps(a.Token.getVendorID(a.Ctx), pi, ps, name)
	if err != nil {
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}
	done(a.Ctx, map[string]interface{}{
		"list":  ds,
		"total": total,
	})
}

// Delete 删除
// DELETE /application
func (a *AppController) Delete() {
	app := new(models.Application)
	if err := parseBody(a.Ctx, app); err != nil {
		badRequest(a.Ctx, err)
		return
	}
	err := a.Service.Delete(app)
	if err != nil {
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}
	done(a.Ctx, "删除成功")
}

// GetBy 获取app信息
// GET /application/{key}
func (a *AppController) GetBy(key string) {
	app, err := a.Service.GetAppInfo(a.Token.getVendorID(a.Ctx), key)
	if err != nil {
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}
	done(a.Ctx, app)
}

// Put 更新
// PUT /application
func (a *AppController) Put() {
	app := new(models.Application)
	if err := parseBody(a.Ctx, app); err != nil {
		badRequest(a.Ctx, err)
		return
	}
	// check update image
	if strings.Contains(app.AppIcon, "tmp") {
		//move image
		args := &rpcs.ArgsMoveFile{
			Source: app.AppIcon,
			Target: "application",
		}
		reply := &rpcs.ReplyMoveFile{}
		err := server.RPCCallByName(nil, "fileaccess", "FileAccess.MoveFile", args, reply)
		if err != nil {
			server.Log.Error(err)
			app.AppIcon = ""
		} else {
			app.AppIcon = reply.FilePath
		}
	}
	if app.AppIcon == "" {
		old, _ := a.Service.GetAppInfo(a.Token.getVendorID(a.Ctx), app.AppKey)
		arg := &rpcs.ArgsDeleteFile{
			FileName: old.AppIcon,
		}
		reply := &rpcs.ReplyEmptyResult{}
		server.RPCCallByName(nil, "fileaccess", "FileAccess.DeleteFile", arg, reply)
	}
	result, err := a.Service.Update(app)
	if err != nil {
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}
	done(a.Ctx, result)
}
