import { graphql } from '../api';
import { releaseFields, actorStashesFields } from '../fragments';
import { curateRelease, curateActor } from '../curate';

function initUiActions(store, _router) {
	function setTagFilter({ commit }, filter) {
		const tagFilter = Array.from(new Set(filter));

		commit('setTagFilter', tagFilter);
		localStorage.setItem('tagFilter', tagFilter);
	}

	function setRange({ commit }, range) {
		commit('setRange', range);
	}

	function setBatch({ commit }, batch) {
		commit('setBatch', batch);
		localStorage.setItem('batch', batch);
	}

	function setTheme({ commit }, theme) {
		commit('setTheme', theme);
		localStorage.setItem('theme', theme);
	}

	async function setSfw({ commit }, sfw) {
		commit('setSfw', sfw);
		localStorage.setItem('sfw', sfw);
	}

	async function search({ _commit }, { query, limit = 20 }) {
		const res = await graphql(`
            query SearchReleases(
                $query: String!
                $limit: Int = 20
				$hasAuth: Boolean!
				$userId: Int
            ) {
                results: searchReleases(
                    query: $query
                    first: $limit
					orderBy: RANK_DESC
					filter: {
						rank: {
							greaterThan: 0.015
						}
					}
                ) {
					release {
						${releaseFields}
					}
					rank
                }
                actors: searchActors(
                    search: $query,
                    first: $limit
                ) {
                    id
                    name
                    slug
                    age
					ageAtDeath
                    dateOfBirth
                    dateOfDeath
                    gender
					aliasFor: actorByAliasFor {
						id
						name
						slug
						age
						ageAtDeath
						dateOfBirth
						dateOfDeath
						gender
						entity {
							id
							name
							slug
						}
						avatar: avatarMedia {
							id
							path
							thumbnail
							lazy
							isS3
							width
							height
							comment
							credit
						}
						birthCountry: countryByBirthCountryAlpha2 {
						  alpha2
						  name
						  alias
						}
					}
                    entity {
                        id
                        name
                        slug
                    }
					avatar: avatarMedia {
						id
						path
						thumbnail
						lazy
						isS3
						width
						height
						comment
						credit
					}
                    birthCountry: countryByBirthCountryAlpha2 {
                      alpha2
                      name
                      alias
                    }
					${actorStashesFields}
                }
            }
        `, {
			query,
			limit,
			hasAuth: !!store.state.auth.user,
			userId: store.state.auth.user?.id,
		});

		return {
			releases: res.results.map(result => curateRelease(result.release)),
			actors: res.actors.map(actor => curateActor(actor)),
		};
	}

	async function fetchStats() {
		const {
			scenes,
			movies,
			actors,
			networks,
			channels,
		} = await graphql(`
            query Stats {
				scenes: releasesConnection(
					last: 1,
					orderBy: BATCH_BY_CREATED_BATCH_ID__CREATED_AT_ASC
				) {
					totalCount
					scenes: nodes {
						batch: createdBatch {
							createdAt
						}
					}
				}
				movies: moviesConnection { totalCount }
				actors: actorsConnection { totalCount }
				networks: entitiesConnection(filter: { type: { equalTo: "network" } }) { totalCount }
				channels: entitiesConnection(filter: { type: { equalTo: "channel" } }) { totalCount }
			}
		`);

		return {
			totalScenes: scenes.totalCount,
			totalMovies: movies.totalCount,
			totalActors: actors.totalCount,
			totalNetworks: networks.totalCount,
			totalChannels: channels.totalCount,
			lastScrape: new Date(scenes.scenes[0]?.batch.createdAt),
		};
	}

	return {
		search,
		setTagFilter,
		setRange,
		setBatch,
		setSfw,
		setTheme,
		fetchStats,
	};
}

export default initUiActions;