<commit_before><?php

namespace GitScrum\Classes;

use Auth;
use Carbon\Carbon;
use GitScrum\Models\User;
use GitScrum\Models\Issue;
use GitScrum\Models\Organization;
use GitScrum\Models\ProductBacklog;
use GitScrum\Models\Branch;
use GitScrum\Contracts\ProviderInterface;
use GuzzleHttp\Client as GuzzleClient;

class Bitbucket implements ProviderInterface
{

    public function tplUser($obj)
    {
        return [
            'provider_id' => $obj->id,
            'provider' => 'bitbucket',
            'username' => $obj->nickname,
            'name' => $obj->name,
            'token' => $obj->token,
            'refresh_token' => $obj->refreshToken,
            'avatar' => $obj->avatar,
            'html_url' => $obj->user['links']['html']['href'],
            'since' => Carbon::parse($obj->user['created_on'])->toDateTimeString(),
            'location' => $obj->user['location'],
            'blog' => $obj->user['website'],
            'email' => $obj->email,
        ];
    }

    public function tplRepository($repo, $slug = false)
    {
        $organization = $this->organization($repo);

        if (!$organization) {
            return;
        }

        return (object) [
            'provider_id' => $repo->uuid,
            'organization_id' => $organization->id,
            'organization_title' => $organization->username,
            'slug' => $repo->slug,
            'title' => $repo->slug,
            'fullname' => $repo->name,
            'is_private' => $repo->is_private,
            'html_url' => $repo->links->html->href,
            'description' => null,
            'fork' => $repo->fork_policy =='allow_forks' ? true : false,
            'url' => $repo->links->self->href,
            'since' =>  Carbon::parse($repo->created_on)->toDateTimeString(),
            'pushed_at' => Carbon::parse($repo->updated_on)->toDateTimeString(),
            'ssh_url' => $repo->links->clone[1]->href,
            'clone_url' => $repo->links->clone[0]->href,
            'homepage' => $repo->links->html->href,
            'default_branch' => isset($repo->mainbranch) ? (isset($repo->mainbranch->name) ? $repo->mainbranch->name : $repo->mainbranch ) : null,
        ];
    }

    public function tplIssue($obj, $productBacklogId)
    {
        if (isset($obj->assignee->username)) {
            $user = User::where('username', $obj->assignee->username)
                ->where('provider', 'bitbucket')->first();
        }

        return [
            'provider_id' => $obj->repository->uuid,
            'user_id' => isset($user->id) ? $user->id : Auth::user()->id,
            'product_backlog_id' => $productBacklogId,
            'effort' => 0,
            'config_issue_effort_id' => 1,
            'issue_type_id' => 1,
            'number' => $obj->id,
            'title' => $obj->title,
            'description' => $obj->content->raw,
            'state' => $obj->state,
            'html_url' => $obj->content->html,
            'created_at' => Carbon::parse($obj->created_on)->toDateTimeString(),
            'updated_at' => Carbon::parse($obj->created_on)->toDateTimeString(),
        ];
    }

    public function tplOrganization($obj)
    {
        return [
            'provider_id' => $obj->uuid,
            'username' => $obj->username,
            'url' => $obj->links->self->href ,
            'repos_url' => $obj->links->repositories->href,
            'events_url' => null,
            'hooks_url' => $obj->links->hooks->href,
            'issues_url' => null,
            'members_url' => null,
            'public_members_url' => null,
            'avatar_url' => $obj->links->avatar->href,
            'description' => null,
            'title' => $obj->display_name,
            'blog' => $obj->website,
            'location' => $obj->location,
            'email' => null,
            'public_repos' => null,
            'html_url' => $obj->links->html->href,
            'total_private_repos' => null,
            'since' => Carbon::parse($obj->created_on)->toDateTimeString(),
            'disk_usage' => null,
            'provider' => 'bitbucket'
        ];
    }

    public function readRepositories($page = 1, &$repos = null)
    {
        $url = env('BITBUCKET_INSTANCE_URI').'/2.0/repositories?token='.Auth::user()->token.'&role=contributor&pagelen=20';

        $repos = $this->assertTokenNotExpired(Helper::request($url), $url);

        $response = collect($repos->values)->map(function ($repo) {
            return $this->tplRepository($repo);
        });

        return $response;
    }

    public function createOrUpdateRepository($owner, $obj, $oldTitle = null)
    {
    }

    public function organization($obj)
    {
        if (!isset($obj->owner)) {
            return false;
        }

        $endPoint = strtolower($obj->owner->type) == 'user' ? 'users' : 'teams';

        $url = env('BITBUCKET_INSTANCE_URI').'/2.0/'.$endPoint.'/' .$obj->owner->username ;

        $response = (object) $this->assertTokenNotExpired(Helper::request($url), $url);

        $data = $this->tplOrganization($response);

        $organization = Organization::updateOrCreate(['provider_id' => $data['provider_id']], $data);

        $organization->users()->sync([Auth::id()]);

        return $organization;
    }


    /**
     * Retrieves all repo collaborators in case the owner is logged in
     *
     * @param $owner
     * @param $repo
     * @param null $providerId
     */
    public function readCollaborators($owner, $repo, $providerId = null)
    {
        $url = env('BITBUCKET_INSTANCE_URI').'/1.0/privileges/'.$owner .'/'.$repo ;

        $collaborators =  $this->assertTokenNotExpired(Helper::request($url), $url);

        if (is_null($collaborators)) {
            return ;
        }

        foreach ($collaborators as $collaborator) {
            $user = User::where('provider', 'bitbucket')->where('username', $collaborator->user->username)->first();

            if (is_null($user)) {
                $url = env('BITBUCKET_INSTANCE_URI').'/2.0/users/' .$collaborator->user->username;

                $user = $this->assertTokenNotExpired(Helper::request($url), $url);

                $data = [
                    'provider_id' => $user->uuid,
                    'provider' => 'bitbucket',
                    'username' => $user->username,
                    'name' => $user->display_name,
                    'avatar' => $user->links->avatar->href,
                    'html_url' => $user->links->html->href,
                    'since' => Carbon::parse($user->created_on)->toDateTimeString(),
                    'location' => $user->location,
                    'blog' => $user->website,
                ];

                $user = User::create($data);
            }<commit_msg>add missing variable plug for a single userId in bitbucket, fixing error<commit_after><?php

namespace GitScrum\Classes;

use Auth;
use Carbon\Carbon;
use GitScrum\Models\User;
use GitScrum\Models\Issue;
use GitScrum\Models\Organization;
use GitScrum\Models\ProductBacklog;
use GitScrum\Models\Branch;
use GitScrum\Contracts\ProviderInterface;
use GuzzleHttp\Client as GuzzleClient;

class Bitbucket implements ProviderInterface
{

    public function tplUser($obj)
    {
        return [
            'provider_id' => $obj->id,
            'provider' => 'bitbucket',
            'username' => $obj->nickname,
            'name' => $obj->name,
            'token' => $obj->token,
            'refresh_token' => $obj->refreshToken,
            'avatar' => $obj->avatar,
            'html_url' => $obj->user['links']['html']['href'],
            'since' => Carbon::parse($obj->user['created_on'])->toDateTimeString(),
            'location' => $obj->user['location'],
            'blog' => $obj->user['website'],
            'email' => $obj->email,
        ];
    }

    public function tplRepository($repo, $slug = false)
    {
        $organization = $this->organization($repo);

        if (!$organization) {
            return;
        }

        return (object) [
            'provider_id' => $repo->uuid,
            'organization_id' => $organization->id,
            'organization_title' => $organization->username,
            'slug' => $repo->slug,
            'title' => $repo->slug,
            'fullname' => $repo->name,
            'is_private' => $repo->is_private,
            'html_url' => $repo->links->html->href,
            'description' => null,
            'fork' => $repo->fork_policy =='allow_forks' ? true : false,
            'url' => $repo->links->self->href,
            'since' =>  Carbon::parse($repo->created_on)->toDateTimeString(),
            'pushed_at' => Carbon::parse($repo->updated_on)->toDateTimeString(),
            'ssh_url' => $repo->links->clone[1]->href,
            'clone_url' => $repo->links->clone[0]->href,
            'homepage' => $repo->links->html->href,
            'default_branch' => isset($repo->mainbranch) ? (isset($repo->mainbranch->name) ? $repo->mainbranch->name : $repo->mainbranch ) : null,
        ];
    }

    public function tplIssue($obj, $productBacklogId)
    {
        if (isset($obj->assignee->username)) {
            $user = User::where('username', $obj->assignee->username)
                ->where('provider', 'bitbucket')->first();
        }

        return [
            'provider_id' => $obj->repository->uuid,
            'user_id' => isset($user->id) ? $user->id : Auth::user()->id,
            'product_backlog_id' => $productBacklogId,
            'effort' => 0,
            'config_issue_effort_id' => 1,
            'issue_type_id' => 1,
            'number' => $obj->id,
            'title' => $obj->title,
            'description' => $obj->content->raw,
            'state' => $obj->state,
            'html_url' => $obj->content->html,
            'created_at' => Carbon::parse($obj->created_on)->toDateTimeString(),
            'updated_at' => Carbon::parse($obj->created_on)->toDateTimeString(),
        ];
    }

    public function tplOrganization($obj)
    {
        return [
            'provider_id' => $obj->uuid,
            'username' => $obj->username,
            'url' => $obj->links->self->href ,
            'repos_url' => $obj->links->repositories->href,
            'events_url' => null,
            'hooks_url' => $obj->links->hooks->href,
            'issues_url' => null,
            'members_url' => null,
            'public_members_url' => null,
            'avatar_url' => $obj->links->avatar->href,
            'description' => null,
            'title' => $obj->display_name,
            'blog' => $obj->website,
            'location' => $obj->location,
            'email' => null,
            'public_repos' => null,
            'html_url' => $obj->links->html->href,
            'total_private_repos' => null,
            'since' => Carbon::parse($obj->created_on)->toDateTimeString(),
            'disk_usage' => null,
            'provider' => 'bitbucket'
        ];
    }

    public function readRepositories($page = 1, &$repos = null)
    {
        $url = env('BITBUCKET_INSTANCE_URI').'/2.0/repositories?token='.Auth::user()->token.'&role=contributor&pagelen=20';

        $repos = $this->assertTokenNotExpired(Helper::request($url), $url);

        $response = collect($repos->values)->map(function ($repo) {
            return $this->tplRepository($repo);
        });

        return $response;
    }

    public function createOrUpdateRepository($owner, $obj, $oldTitle = null)
    {
    }

    public function organization($obj)
    {
        if (!isset($obj->owner)) {
            return false;
        }

        $endPoint = strtolower($obj->owner->type) == 'user' ? 'users' : 'teams';

        $url = env('BITBUCKET_INSTANCE_URI').'/2.0/'.$endPoint.'/' .$obj->owner->username ;

        $response = (object) $this->assertTokenNotExpired(Helper::request($url), $url);

        $data = $this->tplOrganization($response);

        $organization = Organization::updateOrCreate(['provider_id' => $data['provider_id']], $data);

        $organization->users()->sync([Auth::id()]);

        return $organization;
    }


    /**
     * Retrieves all repo collaborators in case the owner is logged in
     *
     * @param $owner
     * @param $repo
     * @param null $providerId
     */
    public function readCollaborators($owner, $repo, $providerId = null)
    {
        $url = env('BITBUCKET_INSTANCE_URI').'/1.0/privileges/'.$owner .'/'.$repo ;

        $collaborators =  $this->assertTokenNotExpired(Helper::request($url), $url);

        $userId = null;

        if (is_null($collaborators)) {
            return ;
        }

        foreach ($collaborators as $collaborator) {
            $user = User::where('provider', 'bitbucket')->where('username', $collaborator->user->username)->first();

            if (is_null($user)) {
                $url = env('BITBUCKET_INSTANCE_URI').'/2.0/users/' .$collaborator->user->username;

                $user = $this->assertTokenNotExpired(Helper::request($url), $url);

                $data = [
                    'provider_id' => $user->uuid,
                    'provider' => 'bitbucket',
                    'username' => $user->username,
                    'name' => $user->display_name,
                    'avatar' => $user->links->avatar->href,
                    'html_url' => $user->links->html->href,
                    'since' => Carbon::parse($user->created_on)->toDateTimeString(),
                    'location' => $user->location,
                    'blog' => $user->website,
                ];

                $user = User::create($data);
            }
{'fraction_non_alphanumeric': 0.17785284182699368, 'fraction_numerical': 0.002349831105889264, 'mean_word_length': 2.0966348340154615, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 399, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6056997', 'n_tokens_mistral': 4136, 'n_tokens_neox': 4003, 'n_words': 645}