package runner

import (
	"bufio"
	"errors"
	"io"
	"os"
	"path/filepath"
	"strings"

	jsoniter "github.com/json-iterator/go"

	"github.com/chainreactors/urlfounder/v2/pkg/resolve"
)

// OutputWriter outputs content to writers.
type OutputWriter struct {
	JSON bool
}

type jsonSourceResult struct {
	Host   string `json:"host"`
	Input  string `json:"input"`
	Source string `json:"source"`
}

type jsonSourceIPResult struct {
	Host       string `json:"host"`
	IP         string `json:"ip"`
	Input      string `json:"input"`
	Source     string `json:"source"`
	StatusCode string `json:"statuscode"`
	UrlTitle   string `json:"urltitle"`
}

type jsonSourcesResult struct {
	Host    string   `json:"host"`
	Input   string   `json:"input"`
	Sources []string `json:"sources"`
}

// NewOutputWriter creates a new OutputWriter
func NewOutputWriter(json bool) *OutputWriter {
	return &OutputWriter{JSON: json}
}

func (o *OutputWriter) createFile(filename string, appendToFile bool) (*os.File, error) {
	if filename == "" {
		return nil, errors.New("empty filename")
	}

	dir := filepath.Dir(filename)

	if dir != "" {
		if _, err := os.Stat(dir); os.IsNotExist(err) {
			err := os.MkdirAll(dir, os.ModePerm)
			if err != nil {
				return nil, err
			}
		}
	}

	var file *os.File
	var err error
	if appendToFile {
		file, err = os.OpenFile(filename, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
	} else {
		file, err = os.Create(filename)
	}
	if err != nil {
		return nil, err
	}

	return file, nil
}

// WriteHostNoWildcard writes the output list of url with nW flag to an io.Writer
func (o *OutputWriter) WriteHostNoWildcard(input string, results map[string]resolve.Result, writer io.Writer) error {
	hosts := make(map[string]resolve.HostEntry)
	for host, result := range results {
		hosts[host] = resolve.HostEntry{Host: result.Host, Source: result.Source}
	}

	return o.WriteHost(input, hosts, writer)
}

// WriteHost writes the output list of url to an io.Writer
func (o *OutputWriter) WriteHost(input string, results map[string]resolve.HostEntry, writer io.Writer) error {
	var err error
	if o.JSON {
		err = writeJSONHost(input, results, writer)
	} else {
		err = writePlainHost(input, results, writer)
	}
	return err
}

func writePlainHost(_ string, results map[string]resolve.HostEntry, writer io.Writer) error {
	bufwriter := bufio.NewWriter(writer)
	sb := &strings.Builder{}

	for _, result := range results {
		sb.WriteString(result.Host)
		sb.WriteString("\n")

		_, err := bufwriter.WriteString(sb.String())
		if err != nil {
			bufwriter.Flush()
			return err
		}
		sb.Reset()
	}
	return bufwriter.Flush()
}

func writeJSONHost(input string, results map[string]resolve.HostEntry, writer io.Writer) error {
	encoder := jsoniter.NewEncoder(writer)

	var data jsonSourceResult
	for _, result := range results {
		data.Host = result.Host
		data.Input = input
		data.Source = result.Source
		err := encoder.Encode(data)
		if err != nil {
			return err
		}
	}
	return nil
}

// WriteSourceHost writes the output list of url to an io.Writer
func (o *OutputWriter) WriteSourceHost(input string, sourceMap map[string]map[string]struct{}, writer io.Writer) error {
	var err error
	if o.JSON {
		err = writeSourceJSONHost(input, sourceMap, writer)
	} else {
		err = writeSourcePlainHost(input, sourceMap, writer)
	}
	return err
}

func writeSourceJSONHost(input string, sourceMap map[string]map[string]struct{}, writer io.Writer) error {
	encoder := jsoniter.NewEncoder(writer)

	var data jsonSourcesResult

	for host, sources := range sourceMap {
		data.Host = host
		data.Input = input
		keys := make([]string, 0, len(sources))
		for source := range sources {
			keys = append(keys, source)
		}
		data.Sources = keys

		err := encoder.Encode(&data)
		if err != nil {
			return err
		}
	}
	return nil
}

func writeSourcePlainHost(_ string, sourceMap map[string]map[string]struct{}, writer io.Writer) error {
	bufwriter := bufio.NewWriter(writer)
	sb := &strings.Builder{}

	for host, sources := range sourceMap {
		sb.WriteString(host)
		sb.WriteString(",[")
		sourcesString := ""
		for source := range sources {
			sourcesString += source + ","
		}
		sb.WriteString(strings.Trim(sourcesString, ", "))
		sb.WriteString("]\n")

		_, err := bufwriter.WriteString(sb.String())
		if err != nil {
			bufwriter.Flush()
			return err
		}
		sb.Reset()
	}
	return bufwriter.Flush()
}

// WriteStatusCode writes the output list of urls request status code to an io.Writer
func (o *OutputWriter) WriteStatusCode(input string, results map[string]resolve.Result, writer io.Writer) error {
	var err error
	if o.JSON {
		err = writeJSONStatusCode(input, results, writer)
	} else {
		err = writePlainStatusCode(input, results, writer)
	}
	return err
}

// writePlainStatusCode writes the plain text output list of urls request status code to an io.Writer
func writePlainStatusCode(_ string, results map[string]resolve.Result, writer io.Writer) error {
	bufwriter := bufio.NewWriter(writer)
	st := &strings.Builder{}

	for _, result := range results {
		st.WriteString(result.Host)
		st.WriteString(" ")
		st.WriteString(result.StatusCode)
		st.WriteString(" ")
		st.WriteString(result.Source)
		st.WriteString("\n")

		_, err := bufwriter.WriteString(st.String())
		if err != nil {
			bufwriter.Flush()
			return err
		}
		st.Reset()
	}
	return bufwriter.Flush()
}

// writeJSONStatusCode writes the JSON output list of urls request status code to an io.Writer
func writeJSONStatusCode(input string, results map[string]resolve.Result, writer io.Writer) error {
	encoder := jsoniter.NewEncoder(writer)

	var data jsonSourceIPResult

	for _, result := range results {
		data.Host = result.Host
		data.StatusCode = result.StatusCode
		data.Input = input
		data.Source = result.Source

		err := encoder.Encode(&data)
		if err != nil {
			return err
		}
	}
	return nil
}

// WriteStatusCodeAndTitle writes the output list of urls titles to an io.Writer
func (o *OutputWriter) WriteStatusCodeAndTitle(input string, results map[string]resolve.Result, writer io.Writer) error {
	var err error
	if o.JSON {
		err = writeJSONStatusCodeAndTitle(input, results, writer)
	} else {
		err = writePlainStatusCodeAndTitle(input, results, writer)
	}
	return err
}

// writePlainStatusCodeAndTitle writes the plain text output list of urls titles to an io.Writer
func writePlainStatusCodeAndTitle(_ string, results map[string]resolve.Result, writer io.Writer) error {
	bufwriter := bufio.NewWriter(writer)
	ut := &strings.Builder{}

	for _, result := range results {
		ut.WriteString(result.Host)
		ut.WriteString(" ")
		ut.WriteString(result.StatusCode)
		ut.WriteString(" ")
		ut.WriteString(result.UrlTitle)
		ut.WriteString(" ")
		ut.WriteString(result.Source)
		ut.WriteString("\n")

		_, err := bufwriter.WriteString(ut.String())
		if err != nil {
			bufwriter.Flush()
			return err
		}
		ut.Reset()
	}
	return bufwriter.Flush()
}

// writeJSONStatusCodeAndTitle writes the JSON output list of urls titles to an io.Writer
func writeJSONStatusCodeAndTitle(input string, results map[string]resolve.Result, writer io.Writer) error {
	encoder := jsoniter.NewEncoder(writer)

	var data jsonSourceIPResult

	for _, result := range results {
		data.Host = result.Host
		data.StatusCode = result.StatusCode
		data.UrlTitle = result.UrlTitle
		data.Input = input
		data.Source = result.Source

		err := encoder.Encode(&data)
		if err != nil {
			return err
		}
	}
	return nil
}
