<commit_before>/// <reference path="../../../../../lib/DefinitelyTyped/angularjs/angular.d.ts"/>

import _ = require("lodash");

import AdhAngularHelpers = require("../../../AngularHelpers/AngularHelpers");
import AdhConfig = require("../../../Config/Config");
import AdhEmbed = require("../../../Embed/Embed");
import AdhHttp = require("../../../Http/Http");
import AdhMapping = require("../../../Mapping/Mapping");
import AdhPermissions = require("../../../Permissions/Permissions");
import AdhPreliminaryNames = require("../../../PreliminaryNames/PreliminaryNames");
import AdhRate = require("../../../Rate/Rate");
import AdhResourceArea = require("../../../ResourceArea/ResourceArea");
import AdhTopLevelState = require("../../../TopLevelState/TopLevelState");
import AdhUtil = require("../../../Util/Util");

import RIBadgeAssignment = require("../../../../Resources_/adhocracy_core/resources/badge/IBadgeAssignment");
import RICommentVersion = require("../../../../Resources_/adhocracy_core/resources/comment/ICommentVersion");
import RIProposal = require("../../../../Resources_/adhocracy_meinberlin/resources/kiezkassen/IProposal");
import RIProposalVersion = require("../../../../Resources_/adhocracy_meinberlin/resources/kiezkassen/IProposalVersion");
import SIBadgeable = require("../../../../Resources_/adhocracy_core/sheets/badge/IBadgeable");
import SIBadgeAssignment = require("../../../../Resources_/adhocracy_core/sheets/badge/IBadgeAssignment");
import SIMetadata = require("../../../../Resources_/adhocracy_core/sheets/metadata/IMetadata");
import SIName = require("../../../../Resources_/adhocracy_core/sheets/name/IName");
import SIPoint = require("../../../../Resources_/adhocracy_core/sheets/geo/IPoint");
import SIPool = require("../../../../Resources_/adhocracy_core/sheets/pool/IPool");
import SIProposal = require("../../../../Resources_/adhocracy_meinberlin/sheets/kiezkassen/IProposal");
import SIRateable = require("../../../../Resources_/adhocracy_core/sheets/rate/IRateable");
import SIVersionable = require("../../../../Resources_/adhocracy_core/sheets/versions/IVersionable");
import SITitle = require("../../../../Resources_/adhocracy_core/sheets/title/ITitle");
import SIDescription = require("../../../../Resources_/adhocracy_core/sheets/description/IDescription");
import SILocationReference = require("../../../../Resources_/adhocracy_core/sheets/geo/ILocationReference");
import SIMultiPolygon = require("../../../../Resources_/adhocracy_core/sheets/geo/IMultiPolygon");

var pkgLocation = "/MeinBerlin/Kiezkassen/Proposal";


export interface IScope extends angular.IScope {
    path? : string;
    options : AdhHttp.IOptions;
    errors? : AdhHttp.IBackendErrorItem[];
    data : {
        title : string;
        budget : number;
        detail : string;
        creatorParticipate : boolean;
        locationText : string;
        address : string;
        creator : string;
        creationDate : string;
        commentCount : number;
        lng : number;
        lat : number;
        polygon: number[][];
        assignments : BadgeAssignment[];
    };
    selectedState? : string;
    resource: RIProposalVersion;
}

export class BadgeAssignment {
    constructor(
        private title : string,
        private description : string,
        private name : string
    ) {}
}

var getBadges = (
    adhHttp : AdhHttp.Service<any>,
    $q : angular.IQService
) => (proposal : RIProposalVersion) : angular.IPromise<BadgeAssignment[]> => {
    return $q.all(_.map(proposal.data[SIBadgeable.nick].assignments, (assignmentPath : string) => {
        return adhHttp.get(assignmentPath).then((assignment : RIBadgeAssignment) => {
            var description = assignment.data[SIDescription.nick].description;
            return adhHttp.get(assignment.data[SIBadgeAssignment.nick].badge).then((badge) => {
                var title = badge.data[SITitle.nick].title;
                var name = badge.data[SIName.nick].name;
                return new BadgeAssignment(title, description, name);
            });
        });
    }));
};

// FIXME: the following functions duplicate some of the adhResourceWidget functionality
// They are an experiment on how adhResourceWidget can be improved.  This duplication
// should be resolved at some point.
var bindPath = (
    adhHttp : AdhHttp.Service<any>,
    adhPermissions : AdhPermissions.Service,
    adhRate : AdhRate.Service,
    adhTopLevelState : AdhTopLevelState.Service,
    $q : angular.IQService
) => (
    scope : IScope,
    pathKey : string = "path"
) : void => {
    scope.$watch(pathKey, (value : string) => {
        if (value) {

            // FIXME: Load resources in parallel (use $q.all)
            adhHttp.get(AdhUtil.parentPath(value), {
                content_type: RICommentVersion.content_type,
                depth: "all",
                tag: "LAST",
                count: true
            }).then((pool) => {
                adhHttp.get(value).then((resource : RIProposalVersion) => {

                    scope.resource = resource;

                    var titleSheet : SITitle.Sheet = resource.data[SITitle.nick];
                    var descriptionSheet : SIDescription.Sheet = resource.data[SIDescription.nick];
                    var mainSheet : SIProposal.Sheet = resource.data[SIProposal.nick];
                    var pointSheet : SIPoint.Sheet = resource.data[SIPoint.nick];
                    var metadataSheet : SIMetadata.Sheet = resource.data[SIMetadata.nick];
                    var rateableSheet : SIRateable.Sheet = resource.data[SIRateable.nick];
                    var poolSheet = pool.data[SIPool.nick];

                    adhRate.fetchAggregatedRates(rateableSheet.post_pool, resource.path).then((rates) => {
                        // FIXME: an adapter should take care of this
                        var ratesPro = rates["1"] || 0;
                        var ratesContra = rates["-1"] || 0;

                        var processUrl = adhTopLevelState.get("processUrl");
                        adhHttp.get(processUrl).then((process) => {
                            var locationUrl = process.data[SILocationReference.nick]["location"];
                            adhHttp.get(locationUrl).then((location) => {
                                var polygon = location.data[SIMultiPolygon.nick]["coordinates"][0][0];
                                getBadges(adhHttp, $q)(resource).then((assignments) => {
                                    var resourceAssignments = assignments;
                                    scope.data = {
                                    title: titleSheet.title,
                                    budget: mainSheet.budget,
                                    detail: descriptionSheet.description,
                                    creatorParticipate: mainSheet.creator_participate,
                                    address: mainSheet.address,
                                    rateCount: ratesPro - ratesContra,
                                    locationText: mainSheet.location_text,
                                    adlocationText: mainSheet.location_text,
                                    creator: metadataSheet.creator,
                                    creationDate: metadataSheet.item_creation_date,
                                    commentCount: poolSheet.count,
                                    lng: pointSheet.coordinates[0],
                                    lat: pointSheet.coordinates[1],
                                    polygon: polygon,
                                    assignments: resourceAssignments
                                };
                                });
                            });
                        });
                    });
                });
            });
        }
        adhPermissions.bindScope(scope, () => scope[pathKey]);
    });
};

var fill = (
    scope : IScope,
    proposalVersion : RIProposalVersion
) : void => {
    proposalVersion.data[SIProposal.nick] = new SIProposal.Sheet({
        budget: scope.data.budget,
        detail: scope.data.detail,
        creator_participate: scope.data.creatorParticipate,
        location_text: scope.data.locationText,
        address: scope.data.address
    });
    proposalVersion.data[SITitle.nick] = new SITitle.Sheet({
        title: scope.data.title
    });
    proposalVersion.data[SIDescription.nick] = new SIDescription.Sheet({<commit_msg>Gardening<commit_after>/// <reference path="../../../../../lib/DefinitelyTyped/angularjs/angular.d.ts"/>

import _ = require("lodash");

import AdhAngularHelpers = require("../../../AngularHelpers/AngularHelpers");
import AdhConfig = require("../../../Config/Config");
import AdhEmbed = require("../../../Embed/Embed");
import AdhHttp = require("../../../Http/Http");
import AdhMapping = require("../../../Mapping/Mapping");
import AdhPermissions = require("../../../Permissions/Permissions");
import AdhPreliminaryNames = require("../../../PreliminaryNames/PreliminaryNames");
import AdhRate = require("../../../Rate/Rate");
import AdhResourceArea = require("../../../ResourceArea/ResourceArea");
import AdhTopLevelState = require("../../../TopLevelState/TopLevelState");
import AdhUtil = require("../../../Util/Util");

import RIBadgeAssignment = require("../../../../Resources_/adhocracy_core/resources/badge/IBadgeAssignment");
import RICommentVersion = require("../../../../Resources_/adhocracy_core/resources/comment/ICommentVersion");
import RIProposal = require("../../../../Resources_/adhocracy_meinberlin/resources/kiezkassen/IProposal");
import RIProposalVersion = require("../../../../Resources_/adhocracy_meinberlin/resources/kiezkassen/IProposalVersion");
import SIBadgeable = require("../../../../Resources_/adhocracy_core/sheets/badge/IBadgeable");
import SIBadgeAssignment = require("../../../../Resources_/adhocracy_core/sheets/badge/IBadgeAssignment");
import SIMetadata = require("../../../../Resources_/adhocracy_core/sheets/metadata/IMetadata");
import SIName = require("../../../../Resources_/adhocracy_core/sheets/name/IName");
import SIPoint = require("../../../../Resources_/adhocracy_core/sheets/geo/IPoint");
import SIPool = require("../../../../Resources_/adhocracy_core/sheets/pool/IPool");
import SIProposal = require("../../../../Resources_/adhocracy_meinberlin/sheets/kiezkassen/IProposal");
import SIRateable = require("../../../../Resources_/adhocracy_core/sheets/rate/IRateable");
import SIVersionable = require("../../../../Resources_/adhocracy_core/sheets/versions/IVersionable");
import SITitle = require("../../../../Resources_/adhocracy_core/sheets/title/ITitle");
import SIDescription = require("../../../../Resources_/adhocracy_core/sheets/description/IDescription");
import SILocationReference = require("../../../../Resources_/adhocracy_core/sheets/geo/ILocationReference");
import SIMultiPolygon = require("../../../../Resources_/adhocracy_core/sheets/geo/IMultiPolygon");

var pkgLocation = "/MeinBerlin/Kiezkassen/Proposal";


export interface IScope extends angular.IScope {
    path? : string;
    options : AdhHttp.IOptions;
    errors? : AdhHttp.IBackendErrorItem[];
    data : {
        title : string;
        budget : number;
        detail : string;
        creatorParticipate : boolean;
        locationText : string;
        address : string;
        creator : string;
        creationDate : string;
        commentCount : number;
        lng : number;
        lat : number;
        polygon: number[][];
        assignments : BadgeAssignment[];
    };
    selectedState? : string;
    resource: RIProposalVersion;
}

export class BadgeAssignment {
    constructor(
        private title : string,
        private description : string,
        private name : string
    ) {}
}

var getBadges = (
    adhHttp : AdhHttp.Service<any>,
    $q : angular.IQService
) => (proposal : RIProposalVersion) : angular.IPromise<BadgeAssignment[]> => {
    return $q.all(_.map(proposal.data[SIBadgeable.nick].assignments, (assignmentPath : string) => {
        return adhHttp.get(assignmentPath).then((assignment : RIBadgeAssignment) => {
            var description = assignment.data[SIDescription.nick].description;
            return adhHttp.get(assignment.data[SIBadgeAssignment.nick].badge).then((badge) => {
                var title = badge.data[SITitle.nick].title;
                var name = badge.data[SIName.nick].name;
                return new BadgeAssignment(title, description, name);
            });
        });
    }));
};

// FIXME: the following functions duplicate some of the adhResourceWidget functionality
// They are an experiment on how adhResourceWidget can be improved.  This duplication
// should be resolved at some point.
var bindPath = (
    adhHttp : AdhHttp.Service<any>,
    adhPermissions : AdhPermissions.Service,
    adhRate : AdhRate.Service,
    adhTopLevelState : AdhTopLevelState.Service,
    $q : angular.IQService
) => (
    scope : IScope,
    pathKey : string = "path"
) : void => {
    scope.$watch(pathKey, (value : string) => {
        if (value) {

            // FIXME: Load resources in parallel (use $q.all)
            adhHttp.get(AdhUtil.parentPath(value), {
                content_type: RICommentVersion.content_type,
                depth: "all",
                tag: "LAST",
                count: true
            }).then((pool) => {
                adhHttp.get(value).then((resource : RIProposalVersion) => {

                    scope.resource = resource;

                    var titleSheet : SITitle.Sheet = resource.data[SITitle.nick];
                    var descriptionSheet : SIDescription.Sheet = resource.data[SIDescription.nick];
                    var mainSheet : SIProposal.Sheet = resource.data[SIProposal.nick];
                    var pointSheet : SIPoint.Sheet = resource.data[SIPoint.nick];
                    var metadataSheet : SIMetadata.Sheet = resource.data[SIMetadata.nick];
                    var rateableSheet : SIRateable.Sheet = resource.data[SIRateable.nick];
                    var poolSheet = pool.data[SIPool.nick];

                    adhRate.fetchAggregatedRates(rateableSheet.post_pool, resource.path).then((rates) => {
                        // FIXME: an adapter should take care of this
                        var ratesPro = rates["1"] || 0;
                        var ratesContra = rates["-1"] || 0;

                        var processUrl = adhTopLevelState.get("processUrl");
                        adhHttp.get(processUrl).then((process) => {
                            var locationUrl = process.data[SILocationReference.nick]["location"];
                            adhHttp.get(locationUrl).then((location) => {
                                var polygon = location.data[SIMultiPolygon.nick]["coordinates"][0][0];
                                getBadges(adhHttp, $q)(resource).then((assignments) => {
                                    scope.data = {
                                        title: titleSheet.title,
                                        budget: mainSheet.budget,
                                        detail: descriptionSheet.description,
                                        creatorParticipate: mainSheet.creator_participate,
                                        address: mainSheet.address,
                                        rateCount: ratesPro - ratesContra,
                                        locationText: mainSheet.location_text,
                                        adlocationText: mainSheet.location_text,
                                        creator: metadataSheet.creator,
                                        creationDate: metadataSheet.item_creation_date,
                                        commentCount: poolSheet.count,
                                        lng: pointSheet.coordinates[0],
                                        lat: pointSheet.coordinates[1],
                                        polygon: polygon,
                                        assignments: assignments
                                    };
                                });
                            });
                        });
                    });
                });
            });
        }
        adhPermissions.bindScope(scope, () => scope[pathKey]);
    });
};

var fill = (
    scope : IScope,
    proposalVersion : RIProposalVersion
) : void => {
    proposalVersion.data[SIProposal.nick] = new SIProposal.Sheet({
        budget: scope.data.budget,
        detail: scope.data.detail,
        creator_participate: scope.data.creatorParticipate,
        location_text: scope.data.locationText,
        address: scope.data.address
    });
    proposalVersion.data[SITitle.nick] = new SITitle.Sheet({
        title: scope.data.title
    });
    proposalVersion.data[SIDescription.nick] = new SIDescription.Sheet({
{'fraction_non_alphanumeric': 0.1388083545352346, 'fraction_numerical': 0.0009466895449973374, 'mean_word_length': 1.9793759915388682, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 43, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 40, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2020169', 'n_tokens_mistral': 4521, 'n_tokens_neox': 4379, 'n_words': 744}