package lintutils

import (
	"go/ast"
	"strings"

	"golang.org/x/tools/go/analysis"
)

const (
	genCommentPrefix    = "// Code generated "
	genCommentSuffix    = " DO NOT EDIT."
	swigComment         = "This file was automatically generated by SWIG (http://www.swig.org)."
	thriftCommentPrefix = "// Autogenerated by Thrift Compiler"
)

// IsGenerated reports whether the source file is generated code
// according the rules from https://golang.org/s/generatedcode.
func IsGenerated(file *ast.File) bool {
	for _, group := range file.Comments {
		for _, comment := range group.List {
			if IsGeneratedComment(comment.Text) {
				return true
			}
		}
	}

	return false
}

func IsGeneratedComment(text string) bool {
	commentText := strings.Trim(text, "\n")

	if strings.Contains(commentText, swigComment) {
		return true
	}

	if strings.HasPrefix(commentText, thriftCommentPrefix) {
		return true
	}

	if !strings.HasPrefix(commentText, genCommentPrefix) {
		return false
	}

	if !strings.HasSuffix(commentText, genCommentSuffix) {
		return false
	}

	if len(commentText) <= len(genCommentPrefix)+len(genCommentSuffix) {
		return false
	}

	return true
}

func IsTest(pass *analysis.Pass, file ast.Node) bool {
	f := pass.Fset.File(file.Pos())
	if f == nil {
		return false
	}

	return strings.HasSuffix(f.Name(), "_test.go")
}
