// File: @openzeppelin/contracts/access/Ownable.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)

pragma solidity ^0.8.0;

import "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * By default, the owner account will be the one that deploys the contract. This
 * can later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    constructor() {
        _transferOwnership(_msgSender());
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions anymore. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby removing any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

// File: @openzeppelin/contracts/utils/Context.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)

pragma solidity ^0.8.0;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }
}

// File: contracts/EscrowDispute.sol



// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.18;

import "@openzeppelin/contracts/access/Ownable.sol";
import "./interfaces/IEscrowDatabase.sol";
import "./interfaces/IVoting.sol";

contract EscrowDispute is Ownable {
    IVoting private _votingContract;
    IEscrowDatabase private _databaseContract;

    struct DisputeStorage {
        uint256[] milestonesId;
        mapping(uint256 => Dispute) disputes;
    }

    struct Dispute {
        address escrowContract;
        uint256 milestoneId;
        address creator;
        bool raiseByBuyer;
        uint256 votingId;
        bool inProcess;
        uint256 refund;
        uint256 creationTime;
    }

    mapping(address => DisputeStorage) private _disputes;
    address[] private _escrowsInDispute;

    fallback() external payable {}

    receive() external payable {}

    modifier onlyEscrowContracts() {
        bool _found = false;

        for (uint256 i = 0; i < _databaseContract.getAllEscrowContracts().length; i++) {
            if (_databaseContract.getAllEscrowContracts()[i] == msg.sender) {
                _found = true;
            }
        }

        require(_found, "The call is only available from the escrow smart contract");
        _;
    }

    function setVotingContract(address _contractAddress) public onlyOwner {
        _votingContract = IVoting(_contractAddress);
    }

    function setDatabaseContract(address _contractAddress) public onlyOwner {
        _databaseContract = IEscrowDatabase(_contractAddress);
    }

    function getEscrowsInDispute() public view returns (address[] memory) {
        return _escrowsInDispute;
    }

    function getRefund(uint256 _milestoneId) public view returns(uint256) {
        return _disputes[msg.sender].disputes[_milestoneId].refund;
    }

    function getRaiseByBuyerOfDispute(uint256 _milestoneId) public view returns(bool) {
        return _disputes[msg.sender].disputes[_milestoneId].raiseByBuyer;
    }

    function getDisputeStatusByAddressAndMilestoneId(address _escrowAddress, uint256 _milestoneId) public view returns(bool) {
        return _disputes[_escrowAddress].disputes[_milestoneId].inProcess;
    }

    function getAllDisputesByAddress(address _escrowAddress) public view returns(Dispute[] memory) {
        uint256 _disputesCounter = 0;

        for (uint256 i = 0; i < _disputes[_escrowAddress].milestonesId.length; i++) {
            _disputesCounter += 1;
        }

        Dispute[] memory _returnArray = new Dispute[](_disputesCounter);

        for (uint256 i = 0; i < _disputes[_escrowAddress].milestonesId.length; i++) {
            _returnArray[i] = _disputes[_escrowAddress].disputes[_disputes[_escrowAddress].milestonesId[i]];
        }

        return _returnArray;
    }

    function raiseDispute(
        uint256 _milestoneId,
        bool _raiseByBuyer,
        address _creator,
        string memory _title,
        string memory _body,
        string[] memory _choices,
        uint64 _start,
        uint64 _end,
        uint256 _refund
    ) public onlyEscrowContracts returns (uint256) {
        require(_disputes[msg.sender].disputes[_milestoneId].votingId == 0, "Dispute for this milestone already created or has been resolved");
        
        Dispute memory dispute = Dispute(
            msg.sender,
            _milestoneId,
            _creator,
            _raiseByBuyer,
            _votingContract.createProposal(_title, _body, _choices, _start, _end),
            true,
            _refund,
            block.timestamp
        );

        _disputes[msg.sender].disputes[_milestoneId] = dispute;

        _disputes[msg.sender].milestonesId.push(_milestoneId);

        _escrowsInDispute.push(msg.sender);

        return _disputes[msg.sender].disputes[_milestoneId].votingId;
    }

    function resolveDispute(
        uint256 _milestoneId, 
        address _caller
    ) public onlyEscrowContracts returns (uint8) {
        require(_caller == _disputes[msg.sender].disputes[_milestoneId].creator, "You are not disput creator");
        require(_disputes[msg.sender].disputes[_milestoneId].inProcess, "Dispute already resolved");

        for (uint256 i = 0; i < _escrowsInDispute.length; i++) {
            if (msg.sender == _escrowsInDispute[i]) {
                _deleteteItemFromEscrowsInDispute(i);
            }
        }

        _disputes[msg.sender].disputes[_milestoneId].inProcess = false;

        return _votingContract.getWinningChoice(_disputes[msg.sender].disputes[_milestoneId].votingId);
    }

    function _deleteteItemFromEscrowsInDispute(uint256 _index) private {
        _escrowsInDispute[_index] = _escrowsInDispute[_escrowsInDispute.length - 1];
        _escrowsInDispute.pop();
    }
}
// File: contracts/interfaces/IEscrowDatabase.sol



// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.18;

interface IEscrowDatabase {
    function escrowCounter() external view returns(uint256);

    function increaseEscrowCounter() external;

    function addAllEscrowContracts(address _allContractAddress) external;

    function addGoodsEscrowContracts(address _goodsContractAddress) external;

    function addEscrowsOfUser(address _address, address _escrowContractAddress) external;

    function deleteFromEscrowsOfUser(address _address, address _escrowContractAddress) external;

    function addServicesEscrowContracts(address _servicesContractAddress) external;

    function addNftEscrowContracts(address _nftContractAddress) external;

    function addSourceCodeEscrowContracts(address _sourceCodeContractAddress) external;

    function addGamblingEscrowContracts(address _gamblingContractAddress) external;
    
    function getAllEscrowContracts() external view returns(address[] memory);

    function getGoodsEscrowContracts() external view returns (address[] memory);

    function getServicesEscrowContracts() external view returns (address[] memory);

    function getNftEscrowContracts() external view returns (address[] memory);

    function getSourceCodeEscrowContracts() external view returns (address[] memory);

    function getGamblingEscrowContracts() external view returns (address[] memory);
}
// File: contracts/interfaces/IVoting.sol



// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.18;

interface IVoting {
    function getWinningChoice(
        uint256 proposalId
    ) external view returns (uint8 choice);

    function createProposal(
        string memory title,
        string memory body,
        string[] memory choices,
        uint64 start,
        uint64 end
    ) external returns (uint256 id);

    function sendVote(uint256 proposalId, uint8 choice) external;
}