package model

import (
	"crawler/config"
	"crawler/service"
	"encoding/json"
	"github.com/google/go-querystring/query"
)

type Kobis struct {
	Rest service.Rest
}

func (this *Kobis) MovieDailyBoxOfficeListAPI(req SearchDailyBoxOfficeParams) (SearchDailyBoxOfficeList, error) {
	var (
		url      = config.MOVIE_DAILY_BOX_OFFICE_LIST
		query, _ = query.Values(req)
		result   SearchDailyBoxOfficeList
	)

	if query.Encode() != "" {
		url += "?" + query.Encode()
	}

	data, err := this.Rest.CallRestGetAPI(url)
	if this.Rest.Check(err) {
		return result, err
	}

	err = json.Unmarshal(data, &result)
	if this.Rest.Check(err) {
		return result, err
	}

	return result, nil
}

func (this *Kobis) MovieWeeklyBoxOfficeListAPI(req SearchWeeklyBoxOfficeParams) (SearchWeeklyBoxOfficeList, error) {
	var (
		url      = config.MOVIE_WEEK_BOX_OFFICE_LIST
		query, _ = query.Values(req)
		result   SearchWeeklyBoxOfficeList
	)

	if query.Encode() != "" {
		url += "?" + query.Encode()
	}

	data, err := this.Rest.CallRestGetAPI(url)
	if this.Rest.Check(err) {
		return result, err
	}

	err = json.Unmarshal(data, &result)
	if this.Rest.Check(err) {
		return result, err
	}

	return result, nil
}

func (this *Kobis) MovieListAPI(req SearchMovieListParams) (SearchMovieList, error) {
	var (
		url      = config.MOVIE_LIST
		query, _ = query.Values(req)
		result   SearchMovieList
	)

	if query.Encode() != "" {
		url += "?" + query.Encode()
	}

	data, err := this.Rest.CallRestGetAPI(url)
	if this.Rest.Check(err) {
		return result, err
	}

	err = json.Unmarshal(data, &result)
	if this.Rest.Check(err) {
		return result, err
	}

	return result, nil
}

func (this *Kobis) MovieInfoAPI(req SearchMovieInfoParams) (SearchMovieInfo, error) {
	var (
		url      = config.MOVIE_INFO
		query, _ = query.Values(req)
		result   SearchMovieInfo
	)

	if query.Encode() != "" {
		url += "?" + query.Encode()
	}

	data, err := this.Rest.CallRestGetAPI(url)
	if this.Rest.Check(err) {
		return result, err
	}

	err = json.Unmarshal(data, &result)
	if this.Rest.Check(err) {
		return result, err
	}

	return result, nil
}

func (this *Kobis) MovieBoxOfficeAPI(req SearchBoxOfficeParams) (SearchBoxOfficeList, error) {
	var (
		url      = config.MOVIE_BOX_OFFICE_STATS
		query, _ = query.Values(req)
		result   SearchBoxOfficeList
	)

	if query.Encode() != "" {
		url += "?" + query.Encode()
	}

	data, err := this.Rest.CallRestGetAPI(url)
	if this.Rest.Check(err) {
		return result, err
	}

	err = json.Unmarshal(data, &result)
	if this.Rest.Check(err) {
		return result, err
	}

	return result, nil
}
