// File: contracts/AlchemyFactory.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "./libraries/CloneLibrary.sol";


/// @author Alchemy Team
/// @title AlchemyFactory
/// @notice Factory contract to create new instances of Alchemy
contract AlchemyFactory {
    using CloneLibrary for address;

    // event that is emitted when a new Alchemy Contract was minted
    event NewAlchemy(address alchemy, address governor, address timelock);

    // the Alchemy governance token
    IERC20 public alch;

    // the factory owner
    address payable public factoryOwner;
    address payable public alchemyRouter;
    address public alchemyImplementation;
    address public governorAlphaImplementation;
    address public timelockImplementation;

    constructor(
        IERC20 _alch,
        address _alchemyImplementation,
        address _governorAlphaImplementation,
        address _timelockImplementation,
        address payable _alchemyRouter
    )
    {
        alch = _alch;
        factoryOwner = msg.sender;
        alchemyImplementation = _alchemyImplementation;
        governorAlphaImplementation = _governorAlphaImplementation;
        timelockImplementation = _timelockImplementation;
        alchemyRouter =_alchemyRouter;
    }

    /**
     * @dev distributes the ALCH token supply
     *
     * @param amount the amount to distribute
    */
    function distributeAlch(uint amount) internal {
        if (alch.balanceOf(address(this)) >= amount) {
            alch.transfer(msg.sender, amount);
        }
    }

    /**
     * @dev mints a new Alchemy Contract
     *
     * @param nftAddress_ the initial nft address to add to the contract
     * @param owner_ the owner of the contract
     * @param tokenId_ the token id of the nft to be added
     * @param totalSupply_ the total supply of the erc20
     * @param name_ the token name
     * @param symbol_ the token symbol
     * @param buyoutPrice_ the buyout price to buyout the dao
     * @param votingPeriod_ the voting period for the DAO in blocks
     * @param timelockDelay_ the timelock delay in seconds
     * @return alchemy - the address of the newly generated alchemy contract
     * governor - the address of the new governor alpha
     * timelock - the address of the new timelock
    */
    function NFTDAOMint(
        IERC721 nftAddress_,
        address owner_,
        uint256 tokenId_,
        uint256 totalSupply_,
        string memory name_,
        string memory symbol_,
        uint256 buyoutPrice_,
        uint256 votingPeriod_,
        uint256 timelockDelay_
    ) public returns (address alchemy, address governor, address timelock) {
        alchemy = alchemyImplementation.createClone();
        governor = governorAlphaImplementation.createClone();
        timelock = timelockImplementation.createClone();

        nftAddress_.transferFrom(msg.sender, alchemy, tokenId_);

        IGovernorAlpha(governor).initialize(
            alchemy,
            timelock,
            totalSupply_,
            votingPeriod_
        );

        ITimelock(timelock).initialize(governor, timelockDelay_);

        IAlchemy(alchemy).initialize(
            nftAddress_,
            owner_,
            tokenId_,
            totalSupply_,
            name_,
            symbol_,
            buyoutPrice_,
            address(this),
            governor,
            timelock
        );

        // distribute gov token
        distributeAlch(100 * 10 ** 18);

        emit NewAlchemy(alchemy, governor, timelock);
    }

    /**
     * @dev lets the owner transfer alch token to another address
     *
     * @param dst the address to send the tokens
     * @param amount the token amount
    */
    function transferAlch(address dst, uint256 amount) external {
        require(msg.sender == factoryOwner, "Only owner");
        alch.transfer(dst, amount);
    }

    /**
     * @dev lets the owner change the ownership to another address
     *
     * @param newOwner the address of the new owner
    */
    function newFactoryOwner(address payable newOwner) external {
        require(msg.sender == factoryOwner, "Only owner");
        factoryOwner = newOwner;
    }

    /**
     * @dev lets the owner change the address to another address
     *
     * @param newAlchemyImplementation_ the new address
    */
    function newAlchemyImplementation(address newAlchemyImplementation_) external {
        require(msg.sender == factoryOwner, "Only owner");
        alchemyImplementation = newAlchemyImplementation_;
    }

    /**
     * @dev lets the owner change the address to another address
     *
     * @param newGovernorAlphaImplementation_ the new address
    */
    function newGovernorAlphaImplementation(address newGovernorAlphaImplementation_) external {
        require(msg.sender == factoryOwner, "Only owner");
        governorAlphaImplementation = newGovernorAlphaImplementation_;
    }

    /**
     * @dev lets the owner change the address to another address
     *
     * @param newTimelockImplementation_ the new address
    */
    function newTimelockImplementation(address newTimelockImplementation_) external {
        require(msg.sender == factoryOwner, "Only owner");
        timelockImplementation = newTimelockImplementation_;
    }

    /**
     * @dev lets the owner change the address to another address
     *
     * @param newRouter the address of the new router
    */
    function newAlchemyRouter(address payable newRouter) external {
        require(msg.sender == factoryOwner, "Only owner");
        alchemyRouter = newRouter;
    }

    /**
     * @dev gets the address of the current alchemy router
     *
     * @return the address of the alchemy router
    */
    function getAlchemyRouter() public view returns (address payable) {
        return alchemyRouter;
    }
}


interface IAlchemy {
    function initialize(
        IERC721 nftAddress_,
        address owner_,
        uint256 tokenId_,
        uint256 totalSupply_,
        string memory name_,
        string memory symbol_,
        uint256 buyoutPrice_,
        address factoryContract,
        address governor_,
        address timelock_
    ) external;
}


interface IGovernorAlpha {
    function initialize(
        address nft_,
        address timelock_,
        uint supply_,
        uint votingPeriod_
    ) external;
}


interface ITimelock {
    function initialize(address admin_, uint delay_) external;
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol



// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0 <0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the amount of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves `amount` tokens from the caller's account to `recipient`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address recipient, uint256 amount) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `sender` to `recipient` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);

    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);
}

// File: @openzeppelin/contracts/token/ERC721/IERC721.sol



// SPDX-License-Identifier: MIT

pragma solidity >=0.6.2 <0.8.0;

import "../../introspection/IERC165.sol";

/**
 * @dev Required interface of an ERC721 compliant contract.
 */
interface IERC721 is IERC165 {
    /**
     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
     */
    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
     */
    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
     */
    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);

    /**
     * @dev Returns the number of tokens in ``owner``'s account.
     */
    function balanceOf(address owner) external view returns (uint256 balance);

    /**
     * @dev Returns the owner of the `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function ownerOf(uint256 tokenId) external view returns (address owner);

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC721 protocol to prevent tokens from being forever locked.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId) external;

    /**
     * @dev Transfers `tokenId` token from `from` to `to`.
     *
     * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 tokenId) external;

    /**
     * @dev Gives permission to `to` to transfer `tokenId` token to another account.
     * The approval is cleared when the token is transferred.
     *
     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
     *
     * Requirements:
     *
     * - The caller must own the token or be an approved operator.
     * - `tokenId` must exist.
     *
     * Emits an {Approval} event.
     */
    function approve(address to, uint256 tokenId) external;

    /**
     * @dev Returns the account approved for `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function getApproved(uint256 tokenId) external view returns (address operator);

    /**
     * @dev Approve or remove `operator` as an operator for the caller.
     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
     *
     * Requirements:
     *
     * - The `operator` cannot be the caller.
     *
     * Emits an {ApprovalForAll} event.
     */
    function setApprovalForAll(address operator, bool _approved) external;

    /**
     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
     *
     * See {setApprovalForAll}
     */
    function isApprovedForAll(address owner, address operator) external view returns (bool);

    /**
      * @dev Safely transfers `tokenId` token from `from` to `to`.
      *
      * Requirements:
      *
      * - `from` cannot be the zero address.
      * - `to` cannot be the zero address.
      * - `tokenId` token must exist and be owned by `from`.
      * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
      * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
      *
      * Emits a {Transfer} event.
      */
    function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}

// File: contracts/libraries/CloneLibrary.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;

/*
The MIT License (MIT)
Copyright (c) 2018 Murray Software, LLC.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
//solhint-disable max-line-length
//solhint-disable no-inline-assembly


/**
 * EIP 1167 Proxy Deployment
 * Originally from https://github.com/optionality/clone-factory/
 */
library CloneLibrary {

    function createClone(address target) internal returns (address result) {
        // Reserve 55 bytes for the deploy code + 17 bytes as a buffer to prevent overwriting
        // other memory in the final mstore
        bytes memory cloneBuffer = new bytes(72);
        assembly {
            let clone := add(cloneBuffer, 32)
            mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
            mstore(add(clone, 0x14), shl(96, target))
            mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
            result := create(0, clone, 0x37)
        }
    }


    function isClone(address target, address query) internal view returns (bool result) {
        assembly {
            let clone := mload(0x40)
            mstore(clone, 0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000)
            mstore(add(clone, 0xa), shl(96, target))
            mstore(add(clone, 0x1e), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)

            let other := add(clone, 0x40)
            extcodecopy(query, other, 0, 0x2d)
            result := and(
                eq(mload(clone), mload(other)),
                eq(mload(add(clone, 0xd)), mload(add(other, 0xd)))
            )
        }
    }
}
// File: @openzeppelin/contracts/introspection/IERC165.sol



// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0 <0.8.0;

/**
 * @dev Interface of the ERC165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[EIP].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}